예제 #1
0
  /** Displays the filters setup dialog to allow customizing file filters in detail. */
  public void optionsSetupFileFiltersMenuItemActionPerformed() {
    FiltersCustomizer dlg =
        new FiltersCustomizer(
            mainWindow,
            false,
            FilterMaster.createDefaultFiltersConfig(),
            FilterMaster.loadConfig(StaticUtils.getConfigDir()),
            null);
    dlg.setVisible(true);
    if (dlg.getReturnStatus() == FiltersCustomizer.RET_OK) {
      // saving config
      FilterMaster.saveConfig(dlg.result, StaticUtils.getConfigDir());

      if (Core.getProject().isProjectLoaded()) {
        if (FilterMaster.loadConfig(Core.getProject().getProjectProperties().getProjectInternal())
            != null) {
          // project specific filters are in place. No need to reload project when
          // non-project-specific filters are changed
          return;
        }
        // asking to reload a project
        int res =
            JOptionPane.showConfirmDialog(
                mainWindow,
                OStrings.getString("MW_REOPEN_QUESTION"),
                OStrings.getString("MW_REOPEN_TITLE"),
                JOptionPane.YES_NO_OPTION);
        if (res == JOptionPane.YES_OPTION) ProjectUICommands.projectReload();
      }
    }
  }
예제 #2
0
 public void projectAccessTMMenuItemActionPerformed() {
   if (!Core.getProject().isProjectLoaded()) {
     return;
   }
   String path = Core.getProject().getProjectProperties().getTMRoot();
   openFile(new File(path));
 }
예제 #3
0
  /** Quits OmegaT */
  public void projectExitMenuItemActionPerformed() {
    boolean projectModified = false;
    if (Core.getProject().isProjectLoaded())
      projectModified = Core.getProject().isProjectModified();

    // RFE 1302358
    // Add Yes/No Warning before OmegaT quits
    if (projectModified || Preferences.isPreference(Preferences.ALWAYS_CONFIRM_QUIT)) {
      if (JOptionPane.YES_OPTION
          != JOptionPane.showConfirmDialog(
              mainWindow,
              OStrings.getString("MW_QUIT_CONFIRM"),
              OStrings.getString("CONFIRM_DIALOG_TITLE"),
              JOptionPane.YES_NO_OPTION)) {
        return;
      }
    }

    flushExportedSegments();

    new SwingWorker<Object, Void>() {
      @Override
      protected Object doInBackground() throws Exception {
        if (Core.getProject().isProjectLoaded()) {
          // Save the list of learned and ignore words
          ISpellChecker sc = Core.getSpellChecker();
          sc.saveWordLists();
          try {
            Core.getProject().saveProject();
          } catch (KnownException ex) {
            // hide exception on shutdown
          }
        }

        CoreEvents.fireApplicationShutdown();

        PluginUtils.unloadPlugins();

        return null;
      }

      @Override
      protected void done() {
        try {
          get();

          MainWindowUI.saveScreenLayout(mainWindow);

          Preferences.save();

          System.exit(0);
        } catch (Exception ex) {
          Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
          Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
        }
      }
    }.execute();
  }
예제 #4
0
  private void addExternalGlossaryEntries(List<GlossaryEntry> result, String src) {

    Language source = Core.getProject().getProjectProperties().getSourceLanguage();
    Language target = Core.getProject().getProjectProperties().getTargetLanguage();

    for (IGlossary gl : externalGlossaries) {
      try {
        result.addAll(gl.search(source, target, src));
      } catch (Exception ex) {
        Log.log(ex);
      }
    }
  }
예제 #5
0
 public void projectAccessWriteableGlossaryMenuItemActionPerformed(int modifier) {
   if (!Core.getProject().isProjectLoaded()) {
     return;
   }
   String path = Core.getProject().getProjectProperties().getWriteableGlossary();
   if (StringUtil.isEmpty(path)) {
     return;
   }
   File toOpen = new File(path);
   if ((modifier & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0) {
     toOpen = toOpen.getParentFile();
   }
   openFile(toOpen);
 }
예제 #6
0
 public void projectAccessCurrentTargetDocumentMenuItemActionPerformed(int modifier) {
   if (!Core.getProject().isProjectLoaded()) {
     return;
   }
   String root = Core.getProject().getProjectProperties().getTargetRoot();
   String path = Core.getEditor().getCurrentTargetFile();
   if (StringUtil.isEmpty(path)) {
     return;
   }
   File toOpen = new File(root, path);
   if ((modifier & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0) {
     toOpen = toOpen.getParentFile();
   }
   openFile(toOpen);
 }
예제 #7
0
  public static void projectReload() {
    UIThreadsUtil.mustBeSwingThread();

    if (!Core.getProject().isProjectLoaded()) {
      return;
    }

    // commit the current entry first
    Core.getEditor().commitAndLeave();

    final ProjectProperties props = Core.getProject().getProjectProperties();

    new SwingWorker<Object, Void>() {
      int previousCurEntryNum = Core.getEditor().getCurrentEntryNumber();

      protected Object doInBackground() throws Exception {
        IMainWindow mainWindow = Core.getMainWindow();
        Cursor hourglassCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
        Cursor oldCursor = mainWindow.getCursor();
        mainWindow.setCursor(hourglassCursor);

        Core.executeExclusively(
            true,
            () -> {
              Core.getProject().saveProject(true);
              ProjectFactory.closeProject();

              ProjectFactory.loadProject(props, true);
            });
        mainWindow.setCursor(oldCursor);
        return null;
      }

      protected void done() {
        try {
          get();
          SwingUtilities.invokeLater(
              () -> {
                // activate entry later - after project will be loaded
                Core.getEditor().gotoEntry(previousCurEntryNum);
                Core.getEditor().requestFocus();
              });
        } catch (Exception ex) {
          processSwingWorkerException(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
        }
      }
    }.execute();
  }
예제 #8
0
  public static void projectSave() {
    UIThreadsUtil.mustBeSwingThread();

    if (!Core.getProject().isProjectLoaded()) {
      return;
    }

    // commit the current entry first
    Core.getEditor().commitAndLeave();

    new SwingWorker<Object, Void>() {
      protected Object doInBackground() throws Exception {
        IMainWindow mainWindow = Core.getMainWindow();
        Cursor hourglassCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
        Cursor oldCursor = mainWindow.getCursor();
        mainWindow.setCursor(hourglassCursor);

        mainWindow.showStatusMessageRB("MW_STATUS_SAVING");

        Core.executeExclusively(true, () -> Core.getProject().saveProject(true));

        mainWindow.showStatusMessageRB("MW_STATUS_SAVED");
        mainWindow.setCursor(oldCursor);
        return null;
      }

      protected void done() {
        try {
          get();
        } catch (Exception ex) {
          processSwingWorkerException(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
        }
      }
    }.execute();
  }
예제 #9
0
  public static void projectCompile() {
    UIThreadsUtil.mustBeSwingThread();

    if (!Core.getProject().isProjectLoaded()) {
      return;
    }

    // commit the current entry first
    Core.getEditor().commitAndLeave();

    new SwingWorker<Object, Void>() {
      protected Object doInBackground() throws Exception {
        Core.executeExclusively(
            true,
            () -> {
              Core.getProject().saveProject(true);
              try {
                Core.getProject().compileProject(".*");
              } catch (Exception ex) {
                throw new RuntimeException(ex);
              }
            });
        return null;
      }

      protected void done() {
        try {
          get();
        } catch (Exception ex) {
          processSwingWorkerException(ex, "TF_COMPILE_ERROR");
        }
      }
    }.execute();
  }
예제 #10
0
  public static Object executeScriptFileHeadless(
      ScriptItem scriptItem, boolean forceFromFile, Map<String, Object> additionalBindings) {
    ScriptEngineManager manager = new ScriptEngineManager(ScriptingWindow.class.getClassLoader());
    ScriptEngine scriptEngine =
        manager.getEngineByExtension(getFileExtension(scriptItem.getName()));

    if (scriptEngine == null) {
      scriptEngine = manager.getEngineByName(DEFAULT_SCRIPT);
    }

    SimpleBindings bindings = new SimpleBindings();
    bindings.put(VAR_PROJECT, Core.getProject());
    bindings.put(VAR_EDITOR, Core.getEditor());
    bindings.put(VAR_GLOSSARY, Core.getGlossary());
    bindings.put(VAR_MAINWINDOW, Core.getMainWindow());
    bindings.put(VAR_RESOURCES, scriptItem.getResourceBundle());

    if (additionalBindings != null) {
      bindings.putAll(additionalBindings);
    }

    Object eval = null;
    try {
      eval = scriptEngine.eval(scriptItem.getText(), bindings);
      if (eval != null) {
        Log.logRB("SCW_SCRIPT_RESULT");
        Log.log(eval.toString());
      }
    } catch (Throwable e) {
      Log.logErrorRB(e, "SCW_SCRIPT_ERROR");
    }

    return eval;
  }
예제 #11
0
  public void editExportSelectionMenuItemActionPerformed() {
    if (!Core.getProject().isProjectLoaded()) return;

    String selection = Core.getEditor().getSelectedText();
    if (selection == null) {
      SourceTextEntry ste = Core.getEditor().getCurrentEntry();
      TMXEntry te = Core.getProject().getTranslationInfo(ste);
      if (te.isTranslated()) {
        selection = te.translation;
      } else {
        selection = ste.getSrcText();
      }
    }

    FileUtil.writeScriptFile(selection, OConsts.SELECTION_EXPORT);
  }
  public void editReplaceInProjectMenuItemActionPerformed() {
    if (!Core.getProject().isProjectLoaded()) return;

    SearchWindowController search = new SearchWindowController(SearchMode.REPLACE);
    mainWindow.addSearchWindow(search);

    search.makeVisible(getTrimmedSelectedTextInMainWindow());
  }
예제 #13
0
  public void editFindInProjectMenuItemActionPerformed() {
    if (!Core.getProject().isProjectLoaded()) return;

    String selection = getTrimmedSelectedTextInMainWindow();

    SearchWindowController search =
        new SearchWindowController(mainWindow, selection, SearchMode.SEARCH);
    mainWindow.addSearchWindow(search);
  }
  /** inserts the source text of a segment at cursor position */
  public void editInsertSourceMenuItemActionPerformed() {
    if (!Core.getProject().isProjectLoaded()) return;

    String toInsert = Core.getEditor().getCurrentEntry().getSrcText();
    if (Preferences.isPreference(Preferences.GLOSSARY_REPLACE_ON_INSERT)) {
      toInsert = EditorUtils.replaceGlossaryEntries(toInsert);
    }
    Core.getEditor().insertText(toInsert);
  }
예제 #15
0
  public static void projectClose() {
    UIThreadsUtil.mustBeSwingThread();

    if (!Core.getProject().isProjectLoaded()) {
      return;
    }

    // commit the current entry first
    Core.getEditor().commitAndLeave();

    new SwingWorker<Object, Void>() {
      protected Object doInBackground() throws Exception {
        Core.getMainWindow().showStatusMessageRB("MW_STATUS_SAVING");

        IMainWindow mainWindow = Core.getMainWindow();
        Cursor hourglassCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
        Cursor oldCursor = mainWindow.getCursor();
        mainWindow.setCursor(hourglassCursor);

        Preferences.save();

        Core.executeExclusively(
            true,
            () -> {
              Core.getProject().saveProject(true);
              ProjectFactory.closeProject();
            });

        Core.getMainWindow().showStatusMessageRB("MW_STATUS_SAVED");
        mainWindow.setCursor(oldCursor);

        // fix - reset progress bar to defaults
        Core.getMainWindow().showLengthMessage(OStrings.getString("MW_SEGMENT_LENGTH_DEFAULT"));
        Core.getMainWindow()
            .showProgressMessage(
                Preferences.getPreferenceEnumDefault(
                            Preferences.SB_PROGRESS_MODE, MainWindowUI.STATUS_BAR_MODE.DEFAULT)
                        == MainWindowUI.STATUS_BAR_MODE.DEFAULT
                    ? OStrings.getString("MW_PROGRESS_DEFAULT")
                    : OStrings.getProgressBarDefaultPrecentageText());

        return null;
      }

      protected void done() {
        try {
          get();
        } catch (Exception ex) {
          processSwingWorkerException(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
        }
        // Restore global prefs in case project had project-specific ones
        Core.setFilterMaster(new FilterMaster(Preferences.getFilters()));
        Core.setSegmenter(new Segmenter(Preferences.getSRX()));
      }
    }.execute();
  }
예제 #16
0
  public static void projectOpenMED() {
    UIThreadsUtil.mustBeSwingThread();

    if (Core.getProject().isProjectLoaded()) {
      return;
    }

    // ask for MED file
    ChooseMedProject ndm = new ChooseMedProject();
    int ndmResult = ndm.showOpenDialog(Core.getMainWindow().getApplicationFrame());
    if (ndmResult != OmegaTFileChooser.APPROVE_OPTION) {
      // user press 'Cancel' in project creation dialog
      return;
    }
    final File med = ndm.getSelectedFile();

    // ask for new project dir
    NewProjectFileChooser ndc = new NewProjectFileChooser();
    int ndcResult = ndc.showSaveDialog(Core.getMainWindow().getApplicationFrame());
    if (ndcResult != OmegaTFileChooser.APPROVE_OPTION) {
      // user press 'Cancel' in project creation dialog
      return;
    }
    final File dir = ndc.getSelectedFile();

    new SwingWorker<Object, Void>() {
      protected Object doInBackground() throws Exception {
        dir.mkdirs();

        final ProjectProperties newProps = new ProjectProperties(dir);
        ProjectMedProcessing.extractFromMed(med, newProps);
        // create project
        try {
          ProjectFactory.createProject(newProps);
        } catch (Exception ex) {
          Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
          Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
        }

        RecentProjects.add(dir.getAbsolutePath());

        return null;
      }

      protected void done() {
        try {
          get();
          SwingUtilities.invokeLater(Core.getEditor()::requestFocus);
        } catch (Exception ex) {
          Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
          Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
        }
      }
    }.execute();
  }
예제 #17
0
  /**
   * Displays the segmentation setup dialog to allow customizing the segmentation rules in detail.
   */
  public void optionsSentsegMenuItemActionPerformed() {
    SegmentationCustomizer segment_window =
        new SegmentationCustomizer(mainWindow, false, SRX.getDefault(), Preferences.getSRX(), null);
    segment_window.setVisible(true);

    if (segment_window.getReturnStatus() == SegmentationCustomizer.RET_OK) {
      Preferences.setSRX(segment_window.getSRX());
      if (Core.getProject().isProjectLoaded()
          && Core.getProject().getProjectProperties().getProjectSRX() == null) {
        // asking to reload a project
        int res =
            JOptionPane.showConfirmDialog(
                mainWindow,
                OStrings.getString("MW_REOPEN_QUESTION"),
                OStrings.getString("MW_REOPEN_TITLE"),
                JOptionPane.YES_NO_OPTION);
        if (res == JOptionPane.YES_OPTION) ProjectUICommands.projectReload();
      }
    }
  }
예제 #18
0
  /** Displays the view options dialog to allow customizing the view options. */
  public void optionsViewOptionsMenuItemActionPerformed() {

    ViewOptionsDialog viewOptions = new ViewOptionsDialog(mainWindow);
    viewOptions.setVisible(true);

    if (viewOptions.getReturnStatus() == ViewOptionsDialog.RET_OK
        && Core.getProject().isProjectLoaded()) {
      // Redisplay according to new view settings
      Core.getEditor().getSettings().updateViewPreferences();
    }
  }
예제 #19
0
  /** Imports the file/files/folder into project's source files. */
  public static void doPromptImportSourceFiles() {
    OmegaTFileChooser chooser = new OmegaTFileChooser();
    chooser.setMultiSelectionEnabled(true);
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    chooser.setDialogTitle(OStrings.getString("TF_FILE_IMPORT_TITLE"));

    int result = chooser.showOpenDialog(Core.getMainWindow().getApplicationFrame());
    if (result == OmegaTFileChooser.APPROVE_OPTION) {
      File[] selFiles = chooser.getSelectedFiles();
      projectImportFiles(Core.getProject().getProjectProperties().getSourceRoot(), selFiles);
    }
  }
  void findInProjectReuseLastWindow() {
    if (!Core.getProject().isProjectLoaded()) {
      return;
    }

    SearchWindowController search = mainWindow.peekLastSearchWindow();
    if (search == null) {
      editFindInProjectMenuItemActionPerformed();
    } else {
      search.makeVisible(getTrimmedSelectedTextInMainWindow());
    }
  }
예제 #21
0
  public void executeScriptFile(
      ScriptItem scriptItem, boolean forceFromFile, Map<String, Object> additionalBindings) {
    ScriptLogger scriptLogger = new ScriptLogger(m_txtResult);

    ScriptEngine scriptEngine =
        manager.getEngineByExtension(getFileExtension(scriptItem.getName()));

    if (scriptEngine == null) {
      scriptEngine = manager.getEngineByName(DEFAULT_SCRIPT);
    }

    // logResult(StaticUtils.format(OStrings.getString("SCW_SELECTED_LANGUAGE"),
    // scriptEngine.getFactory().getEngineName()));
    SimpleBindings bindings = new SimpleBindings();
    bindings.put(VAR_PROJECT, Core.getProject());
    bindings.put(VAR_EDITOR, Core.getEditor());
    bindings.put(VAR_GLOSSARY, Core.getGlossary());
    bindings.put(VAR_MAINWINDOW, Core.getMainWindow());
    bindings.put(VAR_CONSOLE, scriptLogger);
    bindings.put(VAR_RESOURCES, scriptItem.getResourceBundle());

    if (additionalBindings != null) {
      bindings.putAll(additionalBindings);
    }

    // evaluate JavaScript code from String
    try {
      String scriptString;
      if (forceFromFile) {
        scriptString = scriptItem.getText();
      } else if ("".equals(m_txtScriptEditor.getText().trim())) {
        scriptString = scriptItem.getText();
        m_txtScriptEditor.setText(scriptString);
      } else {
        scriptString = m_txtScriptEditor.getText();
      }

      if (!scriptString.endsWith("\n")) {
        scriptString += "\n";
      }

      Object eval = scriptEngine.eval(scriptString, bindings);
      if (eval != null) {
        logResult(OStrings.getString("SCW_SCRIPT_RESULT"));
        logResult(eval.toString());
      }
    } catch (Throwable e) {
      logResult(OStrings.getString("SCW_SCRIPT_ERROR"));
      logResult(e.getMessage());
      // e.printStackTrace();
    }
  }
예제 #22
0
  /** Opens the spell checking window */
  public void optionsSpellCheckMenuItemActionPerformed() {
    Language currentLanguage;
    if (Core.getProject().isProjectLoaded()) {
      currentLanguage = Core.getProject().getProjectProperties().getTargetLanguage();
    } else {
      currentLanguage = new Language(Preferences.getPreference(Preferences.TARGET_LOCALE));
    }
    SpellcheckerConfigurationDialog sd =
        new SpellcheckerConfigurationDialog(mainWindow, currentLanguage);

    sd.setVisible(true);

    if (sd.getReturnStatus() == SpellcheckerConfigurationDialog.RET_OK) {
      boolean isNeedToSpell = Preferences.isPreference(Preferences.ALLOW_AUTO_SPELLCHECKING);
      if (isNeedToSpell && Core.getProject().isProjectLoaded()) {
        ISpellChecker sc = Core.getSpellChecker();
        sc.destroy();
        sc.initialize();
      }
      Core.getEditor().getSettings().setAutoSpellChecking(isNeedToSpell);
    }
  }
예제 #23
0
 /** Prompt the user to reload the current project */
 public static void promptReload() {
   if (!Core.getProject().isProjectLoaded()) {
     return;
   }
   // asking to reload a project
   int res =
       JOptionPane.showConfirmDialog(
           Core.getMainWindow().getApplicationFrame(),
           OStrings.getString("MW_REOPEN_QUESTION"),
           OStrings.getString("MW_REOPEN_TITLE"),
           JOptionPane.YES_NO_OPTION);
   if (res == JOptionPane.YES_OPTION) {
     projectReload();
   }
 }
예제 #24
0
  /** Displays the external TMX dialog to allow customizing the external TMX options. */
  public void optionsExtTMXMenuItemActionPerformed() {

    ExternalTMXMatchesDialog externalTMXOptions = new ExternalTMXMatchesDialog(mainWindow);
    externalTMXOptions.setVisible(true);

    if (externalTMXOptions.getReturnStatus() == ExternalTMXMatchesDialog.RET_OK
        && Core.getProject().isProjectLoaded()) {
      // asking to reload a project
      int res =
          JOptionPane.showConfirmDialog(
              mainWindow,
              OStrings.getString("MW_REOPEN_QUESTION"),
              OStrings.getString("MW_REOPEN_TITLE"),
              JOptionPane.YES_NO_OPTION);
      if (res == JOptionPane.YES_OPTION) ProjectUICommands.projectReload();
    }
  }
예제 #25
0
  /**
   * Copy the specified files to the specified destination, then reload if indicated. Note that a
   * modal dialog will be shown if any of the specified files would be overwritten.
   *
   * @param destination The path to copy the files to
   * @param toImport Files to copy to destination path
   * @param doReload If true, the project will be reloaded after the files are successfully copied
   */
  public static void projectImportFiles(String destination, File[] toImport, boolean doReload) {
    UIThreadsUtil.mustBeSwingThread();

    if (!Core.getProject().isProjectLoaded()) {
      return;
    }

    // commit the current entry first
    Core.getEditor().commitAndLeave();

    try {
      FileUtil.copyFilesTo(new File(destination), toImport, new CollisionCallback());
      if (doReload) {
        projectReload();
      }
    } catch (IOException ioe) {
      Core.getMainWindow().displayErrorRB(ioe, "MAIN_ERROR_File_Import_Failed");
    }
  }
예제 #26
0
 /** Does wikiread */
 public static void doWikiImport() {
   String remote_url =
       JOptionPane.showInputDialog(
           Core.getMainWindow().getApplicationFrame(),
           OStrings.getString("TF_WIKI_IMPORT_PROMPT"),
           OStrings.getString("TF_WIKI_IMPORT_TITLE"),
           JOptionPane.OK_CANCEL_OPTION);
   String projectsource = Core.getProject().getProjectProperties().getSourceRoot();
   if (remote_url == null || remote_url.trim().isEmpty()) {
     // [1762625] Only try to get MediaWiki page if a string has been entered
     return;
   }
   try {
     WikiGet.doWikiGet(remote_url, projectsource);
     projectReload();
   } catch (Exception ex) {
     Log.log(ex);
     Core.getMainWindow().displayErrorRB(ex, "TF_WIKI_IMPORT_FAILED");
   }
 }
예제 #27
0
  /**
   * Displays the tag validation setup dialog to allow customizing the diverse tag validation
   * options.
   */
  public void optionsTagValidationMenuItemActionPerformed() {
    TagProcessingOptionsDialog tagProcessingOptionsDialog =
        new TagProcessingOptionsDialog(mainWindow);
    tagProcessingOptionsDialog.setVisible(true);

    if (tagProcessingOptionsDialog.getReturnStatus() == TagProcessingOptionsDialog.RET_OK
        && Core.getProject().isProjectLoaded()) {
      // Redisplay according to new view settings
      Core.getEditor().getSettings().updateTagValidationPreferences();

      // asking to reload a project
      int res =
          JOptionPane.showConfirmDialog(
              mainWindow,
              OStrings.getString("MW_REOPEN_QUESTION"),
              OStrings.getString("MW_REOPEN_TITLE"),
              JOptionPane.YES_NO_OPTION);
      if (res == JOptionPane.YES_OPTION) {
        ProjectUICommands.projectReload();
      }
    }
  }
예제 #28
0
  public static void projectCreate() {
    UIThreadsUtil.mustBeSwingThread();

    if (Core.getProject().isProjectLoaded()) {
      return;
    }

    // ask for new project dir
    NewProjectFileChooser ndc = new NewProjectFileChooser();
    int ndcResult = ndc.showSaveDialog(Core.getMainWindow().getApplicationFrame());
    if (ndcResult != OmegaTFileChooser.APPROVE_OPTION) {
      // user press 'Cancel' in project creation dialog
      return;
    }
    final File dir = ndc.getSelectedFile();

    new SwingWorker<Object, Void>() {
      protected Object doInBackground() throws Exception {

        dir.mkdirs();

        // ask about new project properties
        ProjectProperties props = new ProjectProperties(dir);
        props.setSourceLanguage(
            Preferences.getPreferenceDefault(Preferences.SOURCE_LOCALE, "EN-US"));
        props.setTargetLanguage(
            Preferences.getPreferenceDefault(Preferences.TARGET_LOCALE, "EN-GB"));
        ProjectPropertiesDialog newProjDialog =
            new ProjectPropertiesDialog(
                Core.getMainWindow().getApplicationFrame(),
                props,
                dir.getAbsolutePath(),
                ProjectPropertiesDialog.Mode.NEW_PROJECT);
        newProjDialog.setVisible(true);
        newProjDialog.dispose();

        IMainWindow mainWindow = Core.getMainWindow();
        Cursor hourglassCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
        Cursor oldCursor = mainWindow.getCursor();
        mainWindow.setCursor(hourglassCursor);

        final ProjectProperties newProps = newProjDialog.getResult();
        if (newProps == null) {
          // user clicks on 'Cancel'
          dir.delete();
          mainWindow.setCursor(oldCursor);
          return null;
        }

        final String projectRoot = newProps.getProjectRoot();

        if (!StringUtil.isEmpty(projectRoot)) {
          // create project
          try {
            ProjectFactory.createProject(newProps);
          } catch (Exception ex) {
            Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
            Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
          }
        }

        RecentProjects.add(dir.getAbsolutePath());

        mainWindow.setCursor(oldCursor);
        return null;
      }
    }.execute();
  }
예제 #29
0
  public static void projectEditProperties() {
    UIThreadsUtil.mustBeSwingThread();

    if (!Core.getProject().isProjectLoaded()) {
      return;
    }

    // commit the current entry first
    Core.getEditor().commitAndLeave();

    // displaying the dialog to change paths and other properties
    ProjectPropertiesDialog prj =
        new ProjectPropertiesDialog(
            Core.getMainWindow().getApplicationFrame(),
            Core.getProject().getProjectProperties(),
            Core.getProject().getProjectProperties().getProjectName(),
            ProjectPropertiesDialog.Mode.EDIT_PROJECT);
    prj.setVisible(true);
    final ProjectProperties newProps = prj.getResult();
    prj.dispose();
    if (newProps == null) {
      return;
    }

    int res =
        JOptionPane.showConfirmDialog(
            Core.getMainWindow().getApplicationFrame(),
            OStrings.getString("MW_REOPEN_QUESTION"),
            OStrings.getString("MW_REOPEN_TITLE"),
            JOptionPane.YES_NO_OPTION);
    if (res != JOptionPane.YES_OPTION) {
      return;
    }

    new SwingWorker<Object, Void>() {
      int previousCurEntryNum = Core.getEditor().getCurrentEntryNumber();

      protected Object doInBackground() throws Exception {
        Core.executeExclusively(
            true,
            () -> {
              Core.getProject().saveProject(true);
              ProjectFactory.closeProject();

              ProjectFactory.loadProject(newProps, true);
            });
        return null;
      }

      protected void done() {
        try {
          get();
          // Make sure to update Editor title
          SwingUtilities.invokeLater(
              () -> {
                // activate entry later - after project will be loaded
                Core.getEditor().gotoEntry(previousCurEntryNum);
                Core.getEditor().requestFocus();
              });
        } catch (Exception ex) {
          processSwingWorkerException(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
        }
      }
    }.execute();
  }
예제 #30
0
  /**
   * Open project. Does nothing if a project is already open and closeCurrent is false.
   *
   * @param projectDirectory project directory or null if user must choose it
   * @param closeCurrent whether or not to close the current project first, if any
   */
  public static void projectOpen(final File projectDirectory, boolean closeCurrent) {
    UIThreadsUtil.mustBeSwingThread();

    if (Core.getProject().isProjectLoaded()) {
      if (closeCurrent) {
        // Register to try again after closing the current project.
        CoreEvents.registerProjectChangeListener(
            new IProjectEventListener() {
              public void onProjectChanged(PROJECT_CHANGE_TYPE eventType) {
                if (eventType == PROJECT_CHANGE_TYPE.CLOSE) {
                  projectOpen(projectDirectory, false);
                  CoreEvents.unregisterProjectChangeListener(this);
                }
              }
            });
        projectClose();
      }
      return;
    }

    final File projectRootFolder;
    if (projectDirectory == null) {
      // select existing project file - open it
      OmegaTFileChooser pfc = new OpenProjectFileChooser();
      if (OmegaTFileChooser.APPROVE_OPTION
          != pfc.showOpenDialog(Core.getMainWindow().getApplicationFrame())) {
        return;
      }
      projectRootFolder = pfc.getSelectedFile();
    } else {
      projectRootFolder = projectDirectory;
    }

    new SwingWorker<Object, Void>() {
      protected Object doInBackground() throws Exception {

        IMainWindow mainWindow = Core.getMainWindow();
        Cursor hourglassCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
        Cursor oldCursor = mainWindow.getCursor();
        mainWindow.setCursor(hourglassCursor);

        try {
          // convert old projects if need
          ConvertProject.convert(projectRootFolder);
        } catch (Exception ex) {
          Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_CONVERT_PROJECT");
          Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_CONVERT_PROJECT");
          mainWindow.setCursor(oldCursor);
          return null;
        }

        // check if project okay
        ProjectProperties props;
        try {
          props = ProjectFileStorage.loadProjectProperties(projectRootFolder.getAbsoluteFile());
        } catch (Exception ex) {
          Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
          Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
          mainWindow.setCursor(oldCursor);
          return null;
        }

        try {
          boolean needToSaveProperties = false;
          if (props.hasRepositories()) {
            // team project - non-exist directories could be created from repo
            props.autocreateDirectories();
          } else {
            // not a team project - ask for non-exist directories
            while (!props.isProjectValid()) {
              needToSaveProperties = true;
              // something wrong with the project - display open dialog
              // to fix it
              ProjectPropertiesDialog prj =
                  new ProjectPropertiesDialog(
                      Core.getMainWindow().getApplicationFrame(),
                      props,
                      new File(projectRootFolder, OConsts.FILE_PROJECT).getAbsolutePath(),
                      ProjectPropertiesDialog.Mode.RESOLVE_DIRS);
              prj.setVisible(true);
              props = prj.getResult();
              prj.dispose();
              if (props == null) {
                // user clicks on 'Cancel'
                mainWindow.setCursor(oldCursor);
                return null;
              }
            }
          }

          final ProjectProperties propsP = props;
          Core.executeExclusively(true, () -> ProjectFactory.loadProject(propsP, true));
          if (needToSaveProperties) {
            Core.getProject().saveProjectProperties();
          }
        } catch (Exception ex) {
          Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
          Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
          mainWindow.setCursor(oldCursor);
          return null;
        }

        RecentProjects.add(projectRootFolder.getAbsolutePath());

        mainWindow.setCursor(oldCursor);
        return null;
      }

      protected void done() {
        try {
          get();
          SwingUtilities.invokeLater(Core.getEditor()::requestFocus);
        } catch (Exception ex) {
          Log.logErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
          Core.getMainWindow().displayErrorRB(ex, "PP_ERROR_UNABLE_TO_READ_PROJECT_FILE");
        }
      }
    }.execute();
  }