OSDN Git Service

localization of application
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / NeverNote.java
index c861eb4..60aeda2 100644 (file)
@@ -63,27 +63,33 @@ import com.trolltech.qt.core.QFile;
 import com.trolltech.qt.core.QFileInfo;
 import com.trolltech.qt.core.QFileSystemWatcher;
 import com.trolltech.qt.core.QIODevice;
+import com.trolltech.qt.core.QIODevice.OpenModeFlag;
+import com.trolltech.qt.core.QLocale;
 import com.trolltech.qt.core.QModelIndex;
 import com.trolltech.qt.core.QSize;
 import com.trolltech.qt.core.QTemporaryFile;
 import com.trolltech.qt.core.QTextCodec;
 import com.trolltech.qt.core.QThreadPool;
 import com.trolltech.qt.core.QTimer;
+import com.trolltech.qt.core.QTranslator;
 import com.trolltech.qt.core.QUrl;
 import com.trolltech.qt.core.Qt;
-import com.trolltech.qt.core.QIODevice.OpenModeFlag;
 import com.trolltech.qt.core.Qt.SortOrder;
 import com.trolltech.qt.core.Qt.WidgetAttribute;
 import com.trolltech.qt.gui.QAbstractItemView;
+import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
 import com.trolltech.qt.gui.QAction;
 import com.trolltech.qt.gui.QApplication;
 import com.trolltech.qt.gui.QCloseEvent;
 import com.trolltech.qt.gui.QColor;
 import com.trolltech.qt.gui.QComboBox;
+import com.trolltech.qt.gui.QComboBox.InsertPolicy;
 import com.trolltech.qt.gui.QCursor;
 import com.trolltech.qt.gui.QDesktopServices;
 import com.trolltech.qt.gui.QDialog;
 import com.trolltech.qt.gui.QFileDialog;
+import com.trolltech.qt.gui.QFileDialog.AcceptMode;
+import com.trolltech.qt.gui.QFileDialog.FileMode;
 import com.trolltech.qt.gui.QGridLayout;
 import com.trolltech.qt.gui.QHBoxLayout;
 import com.trolltech.qt.gui.QIcon;
@@ -93,11 +99,13 @@ import com.trolltech.qt.gui.QListWidget;
 import com.trolltech.qt.gui.QMainWindow;
 import com.trolltech.qt.gui.QMenu;
 import com.trolltech.qt.gui.QMessageBox;
+import com.trolltech.qt.gui.QMessageBox.StandardButton;
 import com.trolltech.qt.gui.QPixmap;
 import com.trolltech.qt.gui.QPrintDialog;
 import com.trolltech.qt.gui.QPrinter;
 import com.trolltech.qt.gui.QProgressBar;
 import com.trolltech.qt.gui.QSizePolicy;
+import com.trolltech.qt.gui.QSizePolicy.Policy;
 import com.trolltech.qt.gui.QSpinBox;
 import com.trolltech.qt.gui.QSplashScreen;
 import com.trolltech.qt.gui.QSplitter;
@@ -107,14 +115,8 @@ import com.trolltech.qt.gui.QTableWidgetItem;
 import com.trolltech.qt.gui.QTextEdit;
 import com.trolltech.qt.gui.QToolBar;
 import com.trolltech.qt.gui.QTreeWidgetItem;
-import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
-import com.trolltech.qt.gui.QComboBox.InsertPolicy;
-import com.trolltech.qt.gui.QFileDialog.AcceptMode;
-import com.trolltech.qt.gui.QFileDialog.FileMode;
-import com.trolltech.qt.gui.QMessageBox.StandardButton;
-import com.trolltech.qt.gui.QSizePolicy.Policy;
-import com.trolltech.qt.webkit.QWebSettings;
 import com.trolltech.qt.webkit.QWebPage.WebAction;
+import com.trolltech.qt.webkit.QWebSettings;
 import com.trolltech.qt.xml.QDomAttr;
 import com.trolltech.qt.xml.QDomDocument;
 import com.trolltech.qt.xml.QDomElement;
@@ -148,10 +150,8 @@ import cx.fbn.nevernote.gui.TableView;
 import cx.fbn.nevernote.gui.TagTreeWidget;
 import cx.fbn.nevernote.gui.Thumbnailer;
 import cx.fbn.nevernote.gui.TrashTreeWidget;
-import cx.fbn.nevernote.signals.DBRunnerSignal;
 import cx.fbn.nevernote.sql.DatabaseConnection;
-import cx.fbn.nevernote.sql.runners.WatchFolderRecord;
-import cx.fbn.nevernote.threads.DBRunner;
+import cx.fbn.nevernote.sql.WatchFolderRecord;
 import cx.fbn.nevernote.threads.IndexRunner;
 import cx.fbn.nevernote.threads.SyncRunner;
 import cx.fbn.nevernote.utilities.AESEncrypter;
@@ -206,7 +206,6 @@ public class NeverNote extends QMainWindow{
     boolean                                    noteDirty;                                      // Has the note been changed?
     boolean                            inkNote;                    // if this is an ink note, it is read only
   
-    QThread                                    dbThread;                                       // Thread to handle DB communication
     ListManager                                listManager;                                    // DB runnable task
     
     List<QTemporaryFile>       tempFiles;                                      // Array of temporary files;
@@ -291,40 +290,14 @@ public class NeverNote extends QMainWindow{
     //***************************************************************
     //***************************************************************
     // Application Constructor 
-       public NeverNote()  {
-                               
-               if (!lockApplication()) {
-                       System.exit(0);
-               }
+       public NeverNote(DatabaseConnection dbConn)  {
+               conn = dbConn;          
+
                thread().setPriority(Thread.MAX_PRIORITY);
                
                logger = new ApplicationLogger("nevernote.log");
                logger.log(logger.HIGH, tr("Starting Application"));
-               conn = new DatabaseConnection(logger, Global.mainThreadId);
-               conn.dbSetup();
-               
-               logger.log(logger.EXTREME, tr("Creating index connection"));    
-               logger.log(logger.EXTREME, tr("Building DB thread"));
-               Global.dbRunnerSignal = new DBRunnerSignal();
-               if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
-                       boolean goodCheck = false;
-                       while (!goodCheck) {
-                               DatabaseLoginDialog dialog = new DatabaseLoginDialog();
-                               dialog.exec();
-                               if (!dialog.okPressed())
-                                       System.exit(0);
-                               Global.cipherPassword = dialog.getPassword();
-                               goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
-                       }
-               }
-               Global.dbRunner = new DBRunner(Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
-               logger.log(logger.EXTREME, tr("Starting DB thread"));
-               dbThread = new QThread(Global.dbRunner, "Database Thread");
-               dbThread.start();
-               logger.log(logger.EXTREME, tr("DB Thread has started"));
-               Global.dbRunnerSignal.start.emit();
-               logger.log(logger.EXTREME, tr("Setting main thread DB connection"));
-               logger.log(logger.EXTREME, tr("main DB thread setup complete."));
+
                conn.checkDatabaseVersion();
                
                // Start building the invalid XML tables
@@ -335,7 +308,16 @@ public class NeverNote extends QMainWindow{
                        Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
                }
                
-               logger.log(logger.EXTREME, tr("Starting GUI build"));
+               logger.log(logger.EXTREME, "Starting GUI build");
+
+               QTranslator qtTranslator = new QTranslator();
+               qtTranslator.load("classpath:/translations/qt_" + QLocale.system().name() + ".qm");
+               QApplication.instance().installTranslator(qtTranslator);
+
+               QTranslator nevernoteTranslator = new QTranslator();
+               nevernoteTranslator.load("classpath:/translations/nevernote_"+QLocale.system().name()+ ".qm");
+               QApplication.instance().installTranslator(nevernoteTranslator);
+
                Global.originalPalette = QApplication.palette();
                QApplication.setStyle(Global.getStyle());
                if (Global.useStandardPalette())
@@ -359,7 +341,7 @@ public class NeverNote extends QMainWindow{
         listManager = new ListManager(conn, logger, Global.mainThreadId);
         
                logger.log(logger.EXTREME, tr("Building index runners & timers"));
-        indexRunner = new IndexRunner("indexRunner.log");
+        indexRunner = new IndexRunner("indexRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
                indexThread = new QThread(indexRunner, "Index Thread");
                indexThread.start();
                
@@ -376,7 +358,7 @@ public class NeverNote extends QMainWindow{
                                
                logger.log(logger.EXTREME, tr("Setting sync thread & timers"));
                syncThreadsReady=1;
-               syncRunner = new SyncRunner("syncRunner.log");
+               syncRunner = new SyncRunner("syncRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
                syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
                syncTimer = new QTimer();
                syncTimer.timeout.connect(this, "syncTimer()");
@@ -619,18 +601,31 @@ public class NeverNote extends QMainWindow{
                QApplication.initialize(args);
                QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
                QSplashScreen splash = new QSplashScreen(pixmap);
+               boolean showSplash;
+               
+               DatabaseConnection dbConn;
 
-               try {
-                   initializeGlobalSettings(args);
-               } catch (InitializationException e) {
-                       QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
-                       return;
-               }
+        try {
+            initializeGlobalSettings(args);
+
+            showSplash = Global.isWindowVisible("SplashScreen");
+            if (showSplash)
+                splash.show();
+
+            dbConn = setupDatabaseConnection();
+
+            // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
+            Global.getFileManager().purgeResDirectory();
+
+        } catch (InitializationException e) {
+            // Fatal
+            e.printStackTrace();
+            QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
+            return;
+        }
+
+        NeverNote application = new NeverNote(dbConn);
 
-               boolean showSplash = Global.isWindowVisible("SplashScreen");
-               if (showSplash) 
-                       splash.show();
-               NeverNote application = new NeverNote();
                application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
                if (Global.wasWindowMaximized())
                        application.showMaximized();
@@ -643,6 +638,30 @@ public class NeverNote extends QMainWindow{
                QApplication.exit();
        }
 
+    /**
+     * Open the internal database, or create if not present
+     *
+     * @throws InitializationException when opening the database fails, e.g. because another process has it locked
+     */
+    private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
+       ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
+       DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
+
+        if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
+            boolean goodCheck = false;
+            while (!goodCheck) {
+                DatabaseLoginDialog dialog = new DatabaseLoginDialog();
+                dialog.exec();
+                if (!dialog.okPressed())
+                    System.exit(0);
+                Global.cipherPassword = dialog.getPassword();
+                goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
+                        Global.getDatabaseUserPassword(), Global.cipherPassword);
+            }
+        }
+        return dbConn;
+    }
+
        private static void initializeGlobalSettings(String[] args) throws InitializationException {
                 StartupConfig startupConfig = new StartupConfig();
 
@@ -755,16 +774,6 @@ public class NeverNote extends QMainWindow{
                        }
                }
 
-               logger.log(logger.EXTREME, "Shutting down database");
-               conn.dbShutdown();
-               logger.log(logger.EXTREME, "Waiting for DB thread to terminate");
-               try {
-                       dbThread.join();
-               } catch (InterruptedException e) {
-                       e.printStackTrace();
-               }
-               logger.log(logger.EXTREME, "DB Thread has terminated");
-               unlockApplication();
                logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
        }
 
@@ -825,62 +834,16 @@ public class NeverNote extends QMainWindow{
            browserWindow.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
            browserWindow.noteSignal.subjectDateChanged.connect(this, "updateListDateSubject(String, QDateTime)");
            browserWindow.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
+           browserWindow.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
            browserWindow.noteSignal.authorChanged.connect(this, "updateListAuthor(String, String)");
+           browserWindow.noteSignal.geoChanged.connect(this, "setNoteDirty()");
            browserWindow.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
            browserWindow.noteSignal.sourceUrlChanged.connect(this, "updateListSourceUrl(String, String)");
            browserWindow.focusLost.connect(this, "saveNote()");
            browserWindow.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
 //         browserWindow.resourceSignal.externalFileEdit.connect(this, "saveResourceLater(String, String)");
        }
-       private boolean lockApplication() {
-                               
-               // NFC TODO: who creates this - H2? should it be parameterized with databaseName like in RDatabaseConnection? 
-               String fileName = Global.getFileManager().getDbDirPath("NeverNote.lock.db");
-//             QFile.remove(fileName);
-               if (QFile.exists(fileName)) {
-                       QMessageBox.question(this, "Lock File Detected",
-                                       "While starting I've found a database lock file.\n" +
-                                       "to prevent multiple instances from accessing the database \n"+
-                                       "at the same time.  Please stop any other program, or (if you\n" +
-                                       "are sure nothing else is using the database) remove the file\n" +
-                                       fileName +".");
-                       return false;
-                       
-               }
-               return true;
-/*             String fileName = Global.currentDir +"nevernote.lock";
 
-               
-               if (QFile.exists(fileName)) {
-                       if (QMessageBox.question(this, "Confirmation",
-                               "While starting I've found a lock file.  This file is used to prevent multiple "+
-                               "instances of this program running at once.  If NeverNote has crashed this " +
-                               "is just a file that wasn't cleaned up and you can safely, "+
-                               "continue, but if there is another instance of this running you are " +
-                               "running the risk of creating problems.\n\n" +
-                               "Are you sure you want to continue?",
-                               QMessageBox.StandardButton.Yes, 
-                               QMessageBox.StandardButton.No)==StandardButton.No.value()) {
-                                       return false;
-                               }
-               }
-               
-               QFile file = new QFile(fileName);
-               file.open(OpenModeFlag.WriteOnly);
-               file.write(new QByteArray("This file is used to prevent multiple instances " +
-                               "of NeverNote running more than once.  " +
-                               "It should be deleted when NeverNote ends"));
-               file.close();
-               return true;
-*/
-       }
-       private void unlockApplication() {
-               // NFC TODO: should this be removed? Looks like H2 now handles the locking, which it will clean up itself. See #lockApplication.
-               String fileName = Global.getFileManager().getHomeDirPath("nevernote.lock");
-               if (QFile.exists(fileName)) {
-                       QFile.remove(fileName);
-               }
-       }
        
 
        //***************************************************************
@@ -943,7 +906,7 @@ public class NeverNote extends QMainWindow{
        }    
        // Load the style sheet
        private void loadStyleSheet() {
-               String fileName = Global.currentDir +"qss"+System.getProperty("file.separator")+ "default.qss";
+               String fileName = Global.getFileManager().getQssDirPath("default.qss");
                QFile file = new QFile(fileName);
                file.open(OpenModeFlag.ReadOnly);
                String styleSheet = file.readAll().toString();
@@ -1507,6 +1470,13 @@ public class NeverNote extends QMainWindow{
        // A note's tags have been updated
        @SuppressWarnings("unused")
        private void updateNoteTags(String guid, List<String> tags) {
+               // Save any new tags.  We'll need them later.
+               List<String> newTags = new ArrayList<String>();
+               for (int i=0; i<tags.size(); i++) {
+                       if (conn.getTagTable().findTagByName(tags.get(i))==null) 
+                               newTags.add(tags.get(i));
+               }
+               
                listManager.saveNoteTags(guid, tags);
                listManager.countTagResults(listManager.getNoteIndex());
                StringBuffer names = new StringBuffer("");
@@ -1518,7 +1488,10 @@ public class NeverNote extends QMainWindow{
                }
                browserWindow.setTag(names.toString());
                noteDirty = true;
-//             tagTree.updateCounts(listManager.getTagCounter());
+               
+               // Now, we need to add any new tags to the tag tree
+               for (int i=0; i<newTags.size(); i++) 
+                       tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
        }
        // Get a string containing all tag names for a note
        private String getTagNamesForNote(Note n) {
@@ -2657,7 +2630,7 @@ public class NeverNote extends QMainWindow{
        logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
     }
        private void updateListNoteNotebook(String guid, String notebook) {
-       logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
+       logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
 
        for (int i=0; i<noteTableView.model.rowCount(); i++) {
                //QModelIndex modelIndex =  noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
@@ -2673,7 +2646,7 @@ public class NeverNote extends QMainWindow{
                        }       
                }
        }
-       logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
+       logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
     }
     // Update a title for a specific note in the list
     @SuppressWarnings("unused")
@@ -3009,7 +2982,7 @@ public class NeverNote extends QMainWindow{
     // Get a note from Evernote (and put it in the browser)
        private void refreshEvernoteNote(boolean reload) {
                logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
-               if (Global.getDisableViewing()) {
+               if (Global.disableViewing) {
                        browserWindow.setEnabled(false);
                        return;
                }
@@ -3778,6 +3751,8 @@ public class NeverNote extends QMainWindow{
         if (f.exists()) {
             return relativePath;
         }
+       if (f.exists())
+               return appl+".png";
        logger.log(logger.HIGH, "Leaving NeverNote.findIcon");
        return "attachment.png";
     }
@@ -3809,7 +3784,7 @@ public class NeverNote extends QMainWindow{
                                        fileDetails = r.getAttributes().getFileName();
                                String contextFileName;
                                FileManager fileManager = Global.getFileManager();
-                                if (fileDetails != null && !fileDetails.equals("")) {
+                if (fileDetails != null && !fileDetails.equals("")) {
                                        enmedia.setAttribute("href", "nnres://" +r.getGuid() +Global.attachmentNameDelimeter +fileDetails);
                                        contextFileName = fileManager.getResDirPath(r.getGuid() + Global.attachmentNameDelimeter + fileDetails);
                                } else { 
@@ -3880,7 +3855,7 @@ public class NeverNote extends QMainWindow{
                                // NFC TODO: should this be a 'file://' URL?
                                newText.setAttribute("src", Global.getFileManager().getImageDirPath(icon));
                                if (goodPreview) {
-                                       // NFC TODO: should this be a 'file://' URL?
+                               // NFC TODO: should this be a 'file://' URL?
                                        newText.setAttribute("src", fileManager.getResDirPath(filePath));
                                        newText.setAttribute("style", "border-style:solid; border-color:green; padding:0.5mm 0.5mm 0.5mm 0.5mm;");
                                }
@@ -4155,9 +4130,6 @@ public class NeverNote extends QMainWindow{
 //             noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
 //             indexRunner.setKeepRunning(Global.keepRunning);
                
-               // Reload the unindexed table  If the dbthread is dead, we are probably shutting down.
-               if (!dbThread.isAlive())
-                       return;
                listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
                for (int i=0; i<noteTableView.model.rowCount(); i++) {
                        QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
@@ -4363,13 +4335,6 @@ public class NeverNote extends QMainWindow{
                } else
                        saveThreadDeadCount=0;
 
-               if (!dbThread.isAlive()) {
-                       dbThreadDeadCount++;
-                       QMessageBox.information(this, "A thread his died.", "It appears as the database thread has died.  I recommend "+
-                       "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry.");
-               } else
-                       dbThreadDeadCount=0;
-
                if (!syncThread.isAlive()) {
                        syncThreadDeadCount++;
                        QMessageBox.information(this, "A thread his died.", "It appears as the synchronization thread has died.  I recommend "+
@@ -4737,7 +4702,6 @@ public class NeverNote extends QMainWindow{
                // Strip URL prefix and base dir path
                String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
                String name = fileName.replace(dPath, "");
-
                int pos = name.lastIndexOf('.');
                String guid = name;
                if (pos > -1) {
@@ -4850,7 +4814,7 @@ public class NeverNote extends QMainWindow{
        //*************************************************
        //* Check database userid & passwords
        //*************************************************
-       public boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
+       private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
                        Connection connection;
                        
                        try {