OSDN Git Service

Cleanup the spell checker dialog.
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / gui / BrowserWindow.java
1 /*\r
2  * This file is part of NeverNote \r
3  * Copyright 2009 Randy Baumgarte\r
4  * \r
5  * This file may be licensed under the terms of of the\r
6  * GNU General Public License Version 2 (the ``GPL'').\r
7  *\r
8  * Software distributed under the License is distributed\r
9  * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either\r
10  * express or implied. See the GPL for the specific language\r
11  * governing rights and limitations.\r
12  *\r
13  * You should have received a copy of the GPL along with this\r
14  * program. If not, go to http://www.gnu.org/licenses/gpl.html\r
15  * or write to the Free Software Foundation, Inc.,\r
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r
17  *\r
18  */\r
19 \r
20 package cx.fbn.nevernote.gui;\r
21 \r
22 import java.io.File;\r
23 import java.io.FileNotFoundException;\r
24 import java.io.IOException;\r
25 import java.net.FileNameMap;\r
26 import java.net.URI;\r
27 import java.net.URLConnection;\r
28 import java.security.MessageDigest;\r
29 import java.security.NoSuchAlgorithmException;\r
30 import java.text.SimpleDateFormat;\r
31 import java.util.ArrayList;\r
32 import java.util.Calendar;\r
33 import java.util.Collections;\r
34 import java.util.Date;\r
35 import java.util.GregorianCalendar;\r
36 import java.util.HashMap;\r
37 import java.util.List;\r
38 import java.util.Locale;\r
39 \r
40 import org.apache.commons.lang.StringUtils;\r
41 \r
42 import com.evernote.edam.limits.Constants;\r
43 import com.evernote.edam.type.Data;\r
44 import com.evernote.edam.type.Note;\r
45 import com.evernote.edam.type.Notebook;\r
46 import com.evernote.edam.type.Resource;\r
47 import com.evernote.edam.type.ResourceAttributes;\r
48 import com.evernote.edam.type.Tag;\r
49 import com.swabunga.spell.engine.SpellDictionary;\r
50 import com.swabunga.spell.engine.SpellDictionaryHashMap;\r
51 import com.swabunga.spell.engine.Word;\r
52 import com.swabunga.spell.event.SpellCheckEvent;\r
53 import com.swabunga.spell.event.SpellCheckListener;\r
54 import com.swabunga.spell.event.SpellChecker;\r
55 import com.swabunga.spell.event.StringWordTokenizer;\r
56 import com.trolltech.qt.core.QByteArray;\r
57 import com.trolltech.qt.core.QDataStream;\r
58 import com.trolltech.qt.core.QDateTime;\r
59 import com.trolltech.qt.core.QEvent;\r
60 import com.trolltech.qt.core.QEvent.Type;\r
61 import com.trolltech.qt.core.QFile;\r
62 import com.trolltech.qt.core.QFileSystemWatcher;\r
63 import com.trolltech.qt.core.QIODevice;\r
64 import com.trolltech.qt.core.QMimeData;\r
65 import com.trolltech.qt.core.QUrl;\r
66 import com.trolltech.qt.core.Qt.Key;\r
67 import com.trolltech.qt.core.Qt.KeyboardModifier;\r
68 import com.trolltech.qt.core.Qt.KeyboardModifiers;\r
69 import com.trolltech.qt.gui.QAction;\r
70 import com.trolltech.qt.gui.QApplication;\r
71 import com.trolltech.qt.gui.QCalendarWidget;\r
72 import com.trolltech.qt.gui.QClipboard;\r
73 import com.trolltech.qt.gui.QColor;\r
74 import com.trolltech.qt.gui.QComboBox;\r
75 import com.trolltech.qt.gui.QDateEdit;\r
76 import com.trolltech.qt.gui.QDesktopServices;\r
77 import com.trolltech.qt.gui.QFileDialog;\r
78 import com.trolltech.qt.gui.QFileDialog.AcceptMode;\r
79 import com.trolltech.qt.gui.QFileDialog.FileMode;\r
80 import com.trolltech.qt.gui.QFontDatabase;\r
81 import com.trolltech.qt.gui.QFormLayout;\r
82 import com.trolltech.qt.gui.QGridLayout;\r
83 import com.trolltech.qt.gui.QHBoxLayout;\r
84 import com.trolltech.qt.gui.QIcon;\r
85 import com.trolltech.qt.gui.QImage;\r
86 import com.trolltech.qt.gui.QKeyEvent;\r
87 import com.trolltech.qt.gui.QKeySequence;\r
88 import com.trolltech.qt.gui.QLabel;\r
89 import com.trolltech.qt.gui.QLineEdit;\r
90 import com.trolltech.qt.gui.QListWidgetItem;\r
91 import com.trolltech.qt.gui.QMatrix;\r
92 import com.trolltech.qt.gui.QMessageBox;\r
93 import com.trolltech.qt.gui.QPushButton;\r
94 import com.trolltech.qt.gui.QShortcut;\r
95 import com.trolltech.qt.gui.QTimeEdit;\r
96 import com.trolltech.qt.gui.QToolButton;\r
97 import com.trolltech.qt.gui.QToolButton.ToolButtonPopupMode;\r
98 import com.trolltech.qt.gui.QVBoxLayout;\r
99 import com.trolltech.qt.gui.QWidget;\r
100 import com.trolltech.qt.network.QNetworkRequest;\r
101 import com.trolltech.qt.webkit.QWebPage;\r
102 import com.trolltech.qt.webkit.QWebPage.WebAction;\r
103 import com.trolltech.qt.webkit.QWebSettings;\r
104 import com.trolltech.qt.webkit.QWebView;\r
105 \r
106 import cx.fbn.nevernote.Global;\r
107 import cx.fbn.nevernote.dialog.EnCryptDialog;\r
108 import cx.fbn.nevernote.dialog.EnDecryptDialog;\r
109 import cx.fbn.nevernote.dialog.GeoDialog;\r
110 import cx.fbn.nevernote.dialog.InsertLinkDialog;\r
111 import cx.fbn.nevernote.dialog.SpellCheck;\r
112 import cx.fbn.nevernote.dialog.TableDialog;\r
113 import cx.fbn.nevernote.dialog.TagAssign;\r
114 import cx.fbn.nevernote.evernote.EnCrypt;\r
115 import cx.fbn.nevernote.signals.NoteResourceSignal;\r
116 import cx.fbn.nevernote.signals.NoteSignal;\r
117 import cx.fbn.nevernote.sql.DatabaseConnection;\r
118 import cx.fbn.nevernote.utilities.ApplicationLogger;\r
119 import cx.fbn.nevernote.utilities.FileUtils;\r
120 \r
121 public class BrowserWindow extends QWidget {\r
122 \r
123         public final QLineEdit titleLabel;\r
124         private final QLineEdit urlText;\r
125         private final QLabel authorLabel;\r
126         private final QLineEdit authorText;\r
127         private final QComboBox geoBox;\r
128         public final TagLineEdit tagEdit;\r
129         public final QLabel tagLabel;\r
130         private final QPushButton urlLabel;\r
131         private final QLabel alteredLabel;\r
132         private final QDateEdit alteredDate;\r
133         private final QTimeEdit alteredTime;\r
134         private final QDateEdit createdDate;\r
135         private final QTimeEdit createdTime;\r
136         private final QLabel subjectLabel;\r
137         private final QDateEdit subjectDate;\r
138         private final QTimeEdit subjectTime;\r
139         public final QComboBox notebookBox;\r
140         private final QLabel notebookLabel;\r
141         private final QLabel createdLabel;\r
142         public final QComboBox fontSize;\r
143         public final QAction    fontSizeAction;\r
144         private boolean extendedOn;\r
145         public boolean buttonsVisible;\r
146         private final String iconPath = new String("classpath:cx/fbn/nevernote/icons/");\r
147         private final ContentView browser;\r
148         private List<Tag> allTags;\r
149         private List<String> currentTags;\r
150         public NoteSignal noteSignal;\r
151         private List<Notebook> notebookList;\r
152         private Note currentNote;\r
153         private String saveNoteTitle;\r
154         private String saveTagList;\r
155         private boolean insideList;\r
156 //      private String selectedText;\r
157         private final DatabaseConnection conn;\r
158         private final QCalendarWidget createdCalendarWidget;\r
159         private final QCalendarWidget alteredCalendarWidget;\r
160         private final QCalendarWidget subjectCalendarWidget;\r
161 \r
162         public final QPushButton undoButton;\r
163         public final QAction    undoAction;\r
164         public final QPushButton redoButton;\r
165         public final QAction    redoAction;\r
166         public final QPushButton cutButton;\r
167         public final QAction    cutAction;\r
168         public final QPushButton copyButton;\r
169         public final QAction    copyAction;\r
170         public final QPushButton pasteButton;\r
171         public final QAction    pasteAction;\r
172         public final QPushButton boldButton;\r
173         public final QAction    boldAction;\r
174         public final QPushButton underlineButton;\r
175         public final QAction    underlineAction;\r
176         public final QPushButton italicButton;\r
177         public final QAction    italicAction;\r
178         public final Signal0 focusLost;\r
179         public final NoteResourceSignal resourceSignal;\r
180 \r
181         public QPushButton rightAlignButton;\r
182         public final QAction    rightAlignAction;\r
183         public QPushButton leftAlignButton;\r
184         public final QAction    leftAlignAction;\r
185         public QPushButton centerAlignButton;\r
186         public final QAction    centerAlignAction;\r
187 \r
188         public final QPushButton strikethroughButton;\r
189         public final QAction    strikethroughAction;\r
190         public final QPushButton hlineButton;\r
191         public final QAction    hlineAction;\r
192         public final QPushButton indentButton;\r
193         public final QAction    indentAction;\r
194         public final QPushButton outdentButton;\r
195         public final QAction    outdentAction;\r
196         public final QPushButton bulletListButton;\r
197         public final QAction    bulletListAction;\r
198         public final QPushButton numberListButton;\r
199         public final QAction    numberListAction;\r
200         public final QPushButton spellCheckButton;\r
201         public final QAction    spellCheckAction;\r
202 \r
203         public final QShortcut focusTitleShortcut;\r
204         public final QShortcut focusTagShortcut;\r
205         public final QShortcut focusNoteShortcut;\r
206         public final QShortcut focusUrlShortcut;\r
207         public final QShortcut focusAuthorShortcut;\r
208         \r
209         public EditorButtonBar buttonLayout;\r
210         public final QComboBox fontList;\r
211         public final QAction    fontListAction;\r
212         public final QToolButton fontColor;\r
213         public final QAction    fontColorAction;\r
214         private final ColorMenu fontColorMenu;\r
215         public final QToolButton fontHilight;\r
216         public final QAction    fontHilightAction;\r
217         private final ColorMenu fontHilightColorMenu;\r
218         public final QFileSystemWatcher fileWatcher;\r
219         public int cursorPosition;\r
220         private boolean forceTextPaste = false;\r
221         private String selectedFile;\r
222         private String currentHyperlink;\r
223         public boolean keepPDFNavigationHidden;\r
224         private final ApplicationLogger logger;\r
225         SpellDictionary dictionary;\r
226     SpellDictionary userDictionary;\r
227     SpellChecker spellChecker;\r
228     SuggestionListener spellListener;\r
229         private final HashMap<String,Integer> previewPageList; \r
230         \r
231         \r
232         public static class SuggestionListener implements SpellCheckListener {\r
233                 public boolean abortSpellCheck = false;\r
234                 public boolean errorsFound = false;\r
235                 private final SpellCheck                spellCheckDialog;\r
236                 private final SpellChecker checker;\r
237                 \r
238                 \r
239                 private final BrowserWindow parent;\r
240                 public SuggestionListener(BrowserWindow parent, SpellChecker checker) {\r
241                         this.parent = parent;\r
242                         spellCheckDialog = new SpellCheck(checker);\r
243                         this.checker = checker;\r
244                 }\r
245                 public void spellingError(SpellCheckEvent event) {\r
246                         errorsFound = true;\r
247                         spellCheckDialog.setWord(event.getInvalidWord());\r
248 \r
249                     List<Word> suggestions = event.getSuggestions();\r
250                     if (suggestions.isEmpty()) {\r
251                        spellCheckDialog.setNoSuggestions(true);\r
252                     } else {\r
253                        spellCheckDialog.setCurrentSuggestion(suggestions.get(0).getWord());\r
254                        for (int i=0; i<suggestions.size(); i++) {\r
255                           spellCheckDialog.addSuggestion(suggestions.get(i).getWord());\r
256                        }\r
257                        spellCheckDialog.setSelectedSuggestion(0);\r
258                     }\r
259                     spellCheckDialog.exec();\r
260                     if (spellCheckDialog.cancelPressed()) {\r
261                         abortSpellCheck = true;\r
262                         return;\r
263                     }\r
264                     if (spellCheckDialog.replacePressed()) {\r
265                         QClipboard clipboard = QApplication.clipboard();\r
266                         clipboard.setText(spellCheckDialog.getReplacementWord()); \r
267                         parent.pasteClicked();\r
268                     }\r
269                  }\r
270         }\r
271 \r
272         \r
273         \r
274         public BrowserWindow(DatabaseConnection c) {\r
275                 logger = new ApplicationLogger("browser.log");\r
276                 logger.log(logger.HIGH, "Setting up browser");\r
277                 \r
278                 fileWatcher = new QFileSystemWatcher();\r
279 //              fileWatcher.fileChanged.connect(this, "fileChanged(String)");\r
280                 noteSignal = new NoteSignal();\r
281                 titleLabel = new QLineEdit();\r
282                 titleLabel.setMaxLength(Constants.EDAM_NOTE_TITLE_LEN_MAX);\r
283                 urlText = new QLineEdit();\r
284                 authorText = new QLineEdit();\r
285                 geoBox = new QComboBox();\r
286                 urlLabel = new QPushButton();\r
287                 urlLabel.clicked.connect(this, "sourceUrlClicked()");\r
288                 authorLabel = new QLabel();\r
289                 conn = c;\r
290                 \r
291                 focusLost = new Signal0();\r
292 \r
293                 tagEdit = new TagLineEdit(allTags);\r
294                 tagLabel = new QLabel("Tags:");\r
295                 tagEdit.focusLost.connect(this, "modifyTagsTyping()");\r
296 \r
297                 createdCalendarWidget = new QCalendarWidget();\r
298                 createdDate = new QDateEdit();\r
299                 createdDate.setDisplayFormat(Global.getDateFormat());\r
300                 createdDate.setCalendarPopup(true);\r
301                 createdDate.setCalendarWidget(createdCalendarWidget);\r
302                 createdTime = new QTimeEdit();\r
303                 createdDate.dateChanged.connect(this, "createdChanged()");\r
304                 createdTime.timeChanged.connect(this, "createdChanged()");\r
305 \r
306                 alteredCalendarWidget = new QCalendarWidget();\r
307                 alteredDate = new QDateEdit();\r
308                 alteredDate.setDisplayFormat(Global.getDateFormat());\r
309                 alteredDate.setCalendarPopup(true);\r
310                 alteredDate.setCalendarWidget(alteredCalendarWidget);\r
311                 alteredTime = new QTimeEdit();\r
312                 alteredLabel = new QLabel("Altered:");\r
313                 alteredDate.dateChanged.connect(this, "alteredChanged()");\r
314                 alteredTime.timeChanged.connect(this, "alteredChanged()");\r
315 \r
316                 subjectCalendarWidget = new QCalendarWidget();\r
317                 subjectDate = new QDateEdit();\r
318                 subjectDate.setDisplayFormat(Global.getDateFormat());\r
319                 subjectDate.setCalendarPopup(true);\r
320                 subjectDate.setCalendarWidget(subjectCalendarWidget);\r
321                 subjectTime = new QTimeEdit();\r
322                 subjectLabel = new QLabel(tr("Subject Date:"));\r
323                 subjectDate.dateChanged.connect(this, "subjectDateTimeChanged()");\r
324                 subjectTime.timeChanged.connect(this, "subjectDateTimeChanged()");\r
325                 authorText.textChanged.connect(this, "authorChanged()");\r
326                 urlText.textChanged.connect(this, "sourceUrlChanged()");\r
327 \r
328                 notebookBox = new QComboBox();\r
329                 notebookLabel = new QLabel(tr("Notebook"));\r
330                 createdLabel = new QLabel(tr("Created:"));\r
331                 // selectedText = new String();\r
332 \r
333                 urlLabel.setVisible(false);\r
334                 urlText.setVisible(false);\r
335                 authorLabel.setVisible(false);\r
336                 \r
337                 geoBox.setVisible(false);\r
338                 geoBox.addItem(new QIcon(iconPath+"globe.png"), "");\r
339                 geoBox.addItem(new String(tr("Set")));\r
340                 geoBox.addItem(new String(tr("Clear")));\r
341                 geoBox.addItem(new String(tr("View On Map")));\r
342                 geoBox.activated.connect(this, "geoBoxChanged()");\r
343                 \r
344                 authorText.setVisible(false);\r
345                 createdDate.setVisible(false);\r
346                 alteredLabel.setVisible(false);\r
347                 //notebookBox.setVisible(false);\r
348                 notebookLabel.setVisible(false);\r
349                 createdLabel.setVisible(false);\r
350                 createdTime.setVisible(false);\r
351                 alteredDate.setVisible(false);\r
352                 alteredTime.setVisible(false);\r
353                 subjectLabel.setVisible(false);\r
354                 subjectDate.setVisible(false);\r
355                 subjectTime.setVisible(false);\r
356                 extendedOn = false;\r
357                 buttonsVisible = true;\r
358                 setAcceptDrops(true);\r
359 \r
360                 browser = new ContentView(this);\r
361                 browser.page().setLinkDelegationPolicy(\r
362                                 QWebPage.LinkDelegationPolicy.DelegateAllLinks);\r
363                 browser.linkClicked.connect(this, "linkClicked(QUrl)");\r
364                 currentHyperlink = "";\r
365                 \r
366                 QVBoxLayout v = new QVBoxLayout();\r
367                 QFormLayout notebookLayout = new QFormLayout();\r
368                 QGridLayout dateLayout = new QGridLayout();\r
369                 titleLabel.setReadOnly(false);\r
370                 titleLabel.editingFinished.connect(this, "titleEdited()");\r
371                 browser.page().contentsChanged.connect(this, "contentChanged()");\r
372                 browser.page().selectionChanged.connect(this, "selectionChanged()");\r
373                 browser.page().mainFrame().javaScriptWindowObjectCleared.connect(this,\r
374                                 "exposeToJavascript()");\r
375 \r
376                 notebookBox.activated.connect(this, "notebookChanged()");\r
377                 resourceSignal = new NoteResourceSignal();\r
378                 \r
379                 QHBoxLayout tagLayout = new QHBoxLayout();\r
380                 v.addWidget(titleLabel, 0);\r
381                 notebookLayout.addRow(notebookLabel, notebookBox);\r
382                 tagLayout.addLayout(notebookLayout, 0);\r
383                 tagLayout.stretch(4);\r
384                 tagLayout.addWidget(tagLabel, 0);\r
385                 tagLayout.addWidget(tagEdit, 1);\r
386                 v.addLayout(tagLayout);\r
387 \r
388                 QHBoxLayout urlLayout = new QHBoxLayout();\r
389                 urlLayout.addWidget(urlLabel, 0);\r
390                 urlLayout.addWidget(urlText, 0);\r
391                 v.addLayout(urlLayout);\r
392 \r
393                 QHBoxLayout authorLayout = new QHBoxLayout();\r
394                 authorLayout.addWidget(authorLabel, 0);\r
395                 authorLayout.addWidget(authorText, 0);\r
396                 authorLayout.addWidget(geoBox);\r
397                 v.addLayout(authorLayout);\r
398 \r
399                 dateLayout.addWidget(createdLabel, 0, 0);\r
400                 dateLayout.addWidget(createdDate, 0, 1);\r
401                 dateLayout.addWidget(createdTime, 0, 2);\r
402                 dateLayout.setColumnStretch(9, 100);\r
403                 dateLayout.addWidget(alteredLabel, 0, 3);\r
404                 dateLayout.addWidget(alteredDate, 0, 4);\r
405                 dateLayout.addWidget(alteredTime, 0, 5);\r
406                 dateLayout.addWidget(subjectLabel, 0, 6);\r
407                 dateLayout.addWidget(subjectDate, 0, 7);\r
408                 dateLayout.addWidget(subjectTime, 0, 8);\r
409                 v.addLayout(dateLayout, 0);\r
410 \r
411                 undoButton = newEditorButton("undo", tr("Undo Change"));\r
412                 redoButton = newEditorButton("redo", tr("Redo Change"));\r
413                 cutButton = newEditorButton("cut", tr("Cut"));\r
414                 copyButton = newEditorButton("copy", tr("Copy"));\r
415                 pasteButton = newEditorButton("paste", tr("Paste"));\r
416                 boldButton = newEditorButton("bold", tr("Bold"));\r
417                 underlineButton = newEditorButton("underline", tr("Underline"));\r
418                 italicButton = newEditorButton("italic", tr("Italic"));\r
419 \r
420                 rightAlignButton = newEditorButton("justifyRight", tr("Right Align"));\r
421                 leftAlignButton = newEditorButton("justifyLeft", tr("Left Align"));\r
422                 centerAlignButton = newEditorButton("justifyCenter", tr("Center Align"));\r
423 \r
424                 strikethroughButton = newEditorButton("strikethrough", tr("Strikethrough"));\r
425                 hlineButton = newEditorButton("hline", tr("Insert Horizontal Line"));\r
426                 indentButton = newEditorButton("indent", tr("Shift Right"));\r
427                 outdentButton = newEditorButton("outdent", tr("Shift Left"));\r
428                 bulletListButton = newEditorButton("bulletList", tr("Bullet List"));\r
429                 numberListButton = newEditorButton("numberList", tr("Number List"));\r
430                 spellCheckButton = newEditorButton("spellCheck", tr("Spell Check"));\r
431 \r
432                 \r
433                 buttonLayout = new EditorButtonBar();\r
434                 v.addWidget(buttonLayout);\r
435                 \r
436                 undoAction = buttonLayout.addWidget(undoButton);\r
437                 buttonLayout.toggleUndoVisible.triggered.connect(this, "toggleUndoVisible(Boolean)");\r
438                 redoAction = buttonLayout.addWidget(redoButton);\r
439                 buttonLayout.toggleRedoVisible.triggered.connect(this, "toggleRedoVisible(Boolean)");\r
440                 \r
441                 buttonLayout.addWidget(newSeparator());\r
442                 cutAction = buttonLayout.addWidget(cutButton);\r
443                 buttonLayout.toggleCutVisible.triggered.connect(this, "toggleCutVisible(Boolean)");\r
444                 copyAction = buttonLayout.addWidget(copyButton);\r
445                 buttonLayout.toggleCopyVisible.triggered.connect(this, "toggleCopyVisible(Boolean)");\r
446                 pasteAction = buttonLayout.addWidget(pasteButton);\r
447                 buttonLayout.togglePasteVisible.triggered.connect(this, "togglePasteVisible(Boolean)");\r
448 \r
449                 buttonLayout.addWidget(newSeparator());\r
450                 boldAction = buttonLayout.addWidget(boldButton);\r
451                 buttonLayout.toggleBoldVisible.triggered.connect(this, "toggleBoldVisible(Boolean)");\r
452                 italicAction = buttonLayout.addWidget(italicButton);\r
453                 buttonLayout.toggleItalicVisible.triggered.connect(this, "toggleItalicVisible(Boolean)");\r
454                 underlineAction = buttonLayout.addWidget(underlineButton);\r
455                 buttonLayout.toggleUnderlineVisible.triggered.connect(this, "toggleUnderlineVisible(Boolean)");\r
456                 strikethroughAction = buttonLayout.addWidget(strikethroughButton);\r
457                 buttonLayout.toggleStrikethroughVisible.triggered.connect(this, "toggleStrikethroughVisible(Boolean)");\r
458 \r
459                 \r
460                 buttonLayout.addWidget(newSeparator());\r
461                 leftAlignAction = buttonLayout.addWidget(leftAlignButton);\r
462                 buttonLayout.toggleLeftAlignVisible.triggered.connect(this, "toggleLeftAlignVisible(Boolean)");\r
463                 centerAlignAction = buttonLayout.addWidget(centerAlignButton);\r
464                 buttonLayout.toggleCenterAlignVisible.triggered.connect(this, "toggleCenterAlignVisible(Boolean)");\r
465                 rightAlignAction = buttonLayout.addWidget(rightAlignButton);\r
466                 buttonLayout.toggleRightAlignVisible.triggered.connect(this, "toggleRightAlignVisible(Boolean)");\r
467 \r
468                 buttonLayout.addWidget(newSeparator());\r
469                 hlineAction = buttonLayout.addWidget(hlineButton);\r
470                 buttonLayout.toggleHLineVisible.triggered.connect(this, "toggleHLineVisible(Boolean)");\r
471 \r
472                 indentAction = buttonLayout.addWidget(indentButton);\r
473                 buttonLayout.toggleIndentVisible.triggered.connect(this, "toggleIndentVisible(Boolean)");\r
474                 outdentAction = buttonLayout.addWidget(outdentButton);\r
475                 buttonLayout.toggleOutdentVisible.triggered.connect(this, "toggleOutdentVisible(Boolean)");\r
476                 bulletListAction = buttonLayout.addWidget(bulletListButton);\r
477                 buttonLayout.toggleBulletListVisible.triggered.connect(this, "toggleBulletListVisible(Boolean)");\r
478                 numberListAction = buttonLayout.addWidget(numberListButton);\r
479                 buttonLayout.toggleNumberListVisible.triggered.connect(this, "toggleNumberListVisible(Boolean)");\r
480 \r
481                 // Setup the font & font size combo boxes\r
482                 buttonLayout.addWidget(newSeparator());\r
483                 fontList = new QComboBox();\r
484                 fontSize = new QComboBox();\r
485                 fontList.setToolTip("Font");\r
486                 fontSize.setToolTip("Font Size");\r
487                 fontList.activated.connect(this, "fontChanged(String)");\r
488                 fontSize.activated.connect(this, "fontSizeChanged(String)");\r
489                 fontListAction = buttonLayout.addWidget(fontList);\r
490                 buttonLayout.toggleFontVisible.triggered.connect(this, "toggleFontListVisible(Boolean)");\r
491                 fontSizeAction = buttonLayout.addWidget(fontSize);\r
492                 buttonLayout.toggleFontSizeVisible.triggered.connect(this, "toggleFontSizeVisible(Boolean)");\r
493                 QFontDatabase fonts = new QFontDatabase();\r
494                 List<String> fontFamilies = fonts.families();\r
495                 for (int i = 0; i < fontFamilies.size(); i++) {\r
496                         fontList.addItem(fontFamilies.get(i));\r
497                         if (i == 0) {\r
498                                 loadFontSize(fontFamilies.get(i));\r
499                         }\r
500                 }\r
501 \r
502 //              buttonLayout.addWidget(newSeparator(), 0);\r
503                 fontColor = newToolButton("fontColor", tr("Font Color"));\r
504                 fontColorMenu = new ColorMenu(this);\r
505                 fontColor.setMenu(fontColorMenu.getMenu());\r
506                 fontColor.setPopupMode(ToolButtonPopupMode.MenuButtonPopup);\r
507                 fontColor.setAutoRaise(false);\r
508                 fontColorMenu.getMenu().triggered.connect(this, "fontColorClicked()");\r
509                 fontColorAction = buttonLayout.addWidget(fontColor);\r
510                 buttonLayout.toggleFontColorVisible.triggered.connect(this, "toggleFontColorVisible(Boolean)");\r
511                 fontHilight = newToolButton("fontHilight", tr("Font Hilight Color"));\r
512                 fontHilight.setPopupMode(ToolButtonPopupMode.MenuButtonPopup);\r
513                 fontHilight.setAutoRaise(false);\r
514                 fontHilightColorMenu = new ColorMenu(this);\r
515                 fontHilightColorMenu.setDefault(QColor.yellow);\r
516                 fontHilight.setMenu(fontHilightColorMenu.getMenu());\r
517                 fontHilightColorMenu.getMenu().triggered.connect(this, "fontHilightClicked()");\r
518                 fontHilightAction = buttonLayout.addWidget(fontHilight);\r
519                 fontHilightColorMenu.setDefault(QColor.yellow);\r
520                 buttonLayout.toggleFontHilight.triggered.connect(this, "toggleFontHilightVisible(Boolean)");\r
521                 \r
522                 spellCheckAction = buttonLayout.addWidget(spellCheckButton);\r
523                 buttonLayout.toggleNumberListVisible.triggered.connect(this, "spellCheckClicked()");\r
524                 buttonLayout.toggleSpellCheck.triggered.connect(this, "toggleSpellCheckVisible(Boolean)");\r
525 \r
526 \r
527 //              buttonLayout.addWidget(new QLabel(), 1);\r
528                 v.addWidget(browser, 1);\r
529                 setLayout(v);\r
530 \r
531                 browser.downloadAttachmentRequested.connect(this,\r
532                                 "downloadAttachment(QNetworkRequest)");\r
533                 browser.downloadImageRequested.connect(this,\r
534                                 "downloadImage(QNetworkRequest)");\r
535                 setTabOrder(notebookBox, tagEdit);\r
536                 setTabOrder(tagEdit, browser);\r
537                 \r
538                 focusNoteShortcut = new QShortcut(this);\r
539                 setupShortcut(focusNoteShortcut, "Focus_Note");\r
540                 focusNoteShortcut.activated.connect(this, "focusNote()");\r
541                 focusTitleShortcut = new QShortcut(this);\r
542                 setupShortcut(focusTitleShortcut, "Focus_Title");\r
543                 focusTitleShortcut.activated.connect(this, "focusTitle()");\r
544                 focusTagShortcut = new QShortcut(this);\r
545                 setupShortcut(focusTagShortcut, "Focus_Tag");\r
546                 focusTagShortcut.activated.connect(this, "focusTag()");\r
547                 focusAuthorShortcut = new QShortcut(this);\r
548                 setupShortcut(focusAuthorShortcut, "Focus_Author");\r
549                 focusAuthorShortcut.activated.connect(this, "focusAuthor()");\r
550                 focusUrlShortcut = new QShortcut(this);\r
551                 setupShortcut(focusUrlShortcut, "Focus_Url");\r
552                 focusUrlShortcut.activated.connect(this, "focusUrl()");\r
553                 \r
554                 browser.page().mainFrame().setTextSizeMultiplier(Global.getTextSizeMultiplier());\r
555                 browser.page().mainFrame().setZoomFactor(Global.getZoomFactor());\r
556                 \r
557                 previewPageList = new HashMap<String,Integer>();\r
558                 \r
559                 browser.page().microFocusChanged.connect(this, "microFocusChanged()");\r
560                 \r
561                 logger.log(logger.HIGH, "Browser setup complete");\r
562         }\r
563 \r
564         \r
565         \r
566         private void setupShortcut(QShortcut action, String text) {\r
567                 if (!Global.shortcutKeys.containsAction(text))\r
568                         return;\r
569                 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));\r
570         }\r
571         \r
572         \r
573 \r
574         \r
575         // Getter for the QWebView\r
576         public QWebView getBrowser() {\r
577                 return browser;\r
578         }\r
579 \r
580         // Block signals while loading data or things are flagged as dirty by\r
581         // mistake\r
582         public void loadingData(boolean val) {\r
583                 logger.log(logger.EXTREME, "Entering BrowserWindow.loadingData() " +val);\r
584                 notebookBox.blockSignals(val);\r
585                 browser.page().blockSignals(val);\r
586                 browser.page().mainFrame().blockSignals(val);\r
587                 titleLabel.blockSignals(val);\r
588                 alteredDate.blockSignals(val);\r
589                 alteredTime.blockSignals(val);\r
590                 createdTime.blockSignals(val);\r
591                 createdDate.blockSignals(val);\r
592                 subjectDate.blockSignals(val);\r
593                 subjectTime.blockSignals(val);\r
594                 urlText.blockSignals(val);\r
595                 authorText.blockSignals(val);\r
596                 if (!val)\r
597                         exposeToJavascript();\r
598                 logger.log(logger.EXTREME, "Exiting BrowserWindow.loadingData() " +val);\r
599         }\r
600 \r
601         // Enable/disable\r
602         public void setReadOnly(boolean v) {\r
603                 setEnabled(true);\r
604                 titleLabel.setEnabled(!v);\r
605                 notebookBox.setEnabled(!v);\r
606                 tagEdit.setEnabled(!v);\r
607                 authorLabel.setEnabled(!v);\r
608                 geoBox.setEnabled(!v);\r
609                 urlText.setEnabled(!v);\r
610                 createdDate.setEnabled(!v);\r
611                 subjectDate.setEnabled(!v);\r
612                 alteredDate.setEnabled(!v);\r
613                 getBrowser().setEnabled(true);\r
614         }\r
615         \r
616         // expose this class to Javascript on the web page\r
617         private void exposeToJavascript() {\r
618                 browser.page().mainFrame().addToJavaScriptWindowObject("jambi", this);\r
619         }\r
620 \r
621         // Custom event queue\r
622         @Override\r
623         public boolean event(QEvent e) {\r
624                 if (e.type().equals(QEvent.Type.FocusOut)) {\r
625                         logger.log(logger.EXTREME, "Focus lost");\r
626                         focusLost.emit();\r
627                 }\r
628                 return super.event(e);\r
629         }\r
630 \r
631         // clear out browser\r
632         public void clear() {\r
633                 logger.log(logger.EXTREME, "Entering BrowserWindow.clear()");\r
634                 setNote(null);\r
635                 browser.setContent(new QByteArray());\r
636                 tagEdit.setText("");\r
637                 tagEdit.tagCompleter.reset();\r
638                 urlLabel.setText(tr("Source URL:"));\r
639                 titleLabel.setText("");\r
640                 logger.log(logger.EXTREME, "Exiting BrowserWindow.clear()");\r
641         }\r
642 \r
643         // get/set current note\r
644         public void setNote(Note n) {\r
645                 currentNote = n;\r
646                 if (n == null)\r
647                         n = new Note();\r
648                 saveNoteTitle = n.getTitle();\r
649 \r
650         }\r
651 \r
652         public Note getNote() {\r
653                 return currentNote;\r
654         }\r
655 \r
656         // New Editor Button\r
657         private QPushButton newEditorButton(String name, String toolTip) {\r
658                 QPushButton button = new QPushButton();\r
659                 QIcon icon = new QIcon(iconPath + name + ".gif");\r
660                 button.setIcon(icon);\r
661                 button.setToolTip(toolTip);\r
662                 button.clicked.connect(this, name + "Clicked()");\r
663                 return button;\r
664         }\r
665         // New Editor Button\r
666         private QToolButton newToolButton(String name, String toolTip) {\r
667                 QToolButton button = new QToolButton();\r
668                 QIcon icon = new QIcon(iconPath + name + ".gif");\r
669                 button.setIcon(icon);\r
670                 button.setToolTip(toolTip);\r
671                 button.clicked.connect(this, name + "Clicked()");\r
672                 return button;\r
673         }\r
674 \r
675         // New Separator\r
676         private QLabel newSeparator() {\r
677                 return new QLabel("   ");\r
678         }\r
679 \r
680         // Set the title in the window\r
681         public void setTitle(String t) {\r
682                 titleLabel.setText(t);\r
683                 saveNoteTitle = t;\r
684                 checkNoteTitle();\r
685         }\r
686 \r
687         // Return the current text title\r
688         public String getTitle() {\r
689                 return titleLabel.text();\r
690         }\r
691 \r
692         // Set the tag name string\r
693         public void setTag(String t) {\r
694                 saveTagList = t;\r
695                 tagEdit.setText(t);\r
696                 tagEdit.tagCompleter.reset();\r
697         }\r
698 \r
699         // Set the source URL\r
700         public void setUrl(String t) {\r
701                 urlLabel.setText(tr("Source URL:\t"));\r
702                 urlText.setText(t);\r
703         }\r
704 \r
705         // The user want's to launch a web browser on the source of the URL\r
706         public void sourceUrlClicked() {\r
707                 // Make sure we have a valid URL\r
708                 if (urlText.text().trim().equals(""))\r
709                         return;\r
710                 \r
711                 String url = urlText.text();\r
712                 if (!url.toLowerCase().startsWith(tr("http://")))\r
713                         url = tr("http://") +url;\r
714                 \r
715         if (!QDesktopServices.openUrl(new QUrl(url))) {\r
716                 logger.log(logger.LOW, "Error opening file :" +url);\r
717         }\r
718         }\r
719         \r
720         public void setAuthor(String t) {\r
721                 authorLabel.setText(tr("Author:\t"));\r
722                 authorText.setText(t);\r
723         }\r
724 \r
725         // Set the creation date\r
726         public void setCreation(long date) {\r
727                 QDateTime dt = new QDateTime();\r
728                 dt.setTime_t((int) (date / 1000));\r
729                 createdDate.setDateTime(dt);\r
730                 createdTime.setDateTime(dt);\r
731                 createdDate.setDisplayFormat(Global.getDateFormat());\r
732                 createdTime.setDisplayFormat(Global.getTimeFormat());\r
733         }\r
734 \r
735         // Set the creation date\r
736         public void setAltered(long date) {\r
737                 QDateTime dt = new QDateTime();\r
738                 dt.setTime_t((int) (date / 1000));\r
739                 alteredDate.setDateTime(dt);\r
740                 alteredTime.setDateTime(dt);\r
741                 alteredDate.setDisplayFormat(Global.getDateFormat());\r
742                 alteredTime.setDisplayFormat(Global.getTimeFormat());\r
743         }\r
744 \r
745         // Set the subject date\r
746         public void setSubjectDate(long date) {\r
747                 QDateTime dt = new QDateTime();\r
748                 dt.setTime_t((int) (date / 1000));\r
749                 subjectDate.setDateTime(dt);\r
750                 subjectTime.setDateTime(dt);\r
751                 subjectDate.setDisplayFormat(Global.getDateFormat());\r
752                 subjectTime.setDisplayFormat(Global.getTimeFormat());\r
753         }\r
754 \r
755         // Toggle the extended attribute information\r
756         public void toggleInformation() {\r
757                 if (extendedOn) {\r
758                         extendedOn = false;\r
759                 } else {\r
760                         extendedOn = true;\r
761                 }\r
762                 urlLabel.setVisible(extendedOn);\r
763                 urlText.setVisible(extendedOn);\r
764                 authorText.setVisible(extendedOn);\r
765                 geoBox.setVisible(extendedOn);\r
766                 authorLabel.setVisible(extendedOn);\r
767                 createdDate.setVisible(extendedOn);\r
768                 createdTime.setVisible(extendedOn);\r
769                 createdLabel.setVisible(extendedOn);\r
770                 alteredLabel.setVisible(extendedOn);\r
771                 alteredDate.setVisible(extendedOn);\r
772                 alteredTime.setVisible(extendedOn);\r
773                 //notebookBox.setVisible(extendedOn);\r
774                 notebookLabel.setVisible(extendedOn);\r
775                 subjectLabel.setVisible(extendedOn);\r
776                 subjectDate.setVisible(extendedOn);\r
777                 subjectTime.setVisible(extendedOn);\r
778         }\r
779 \r
780         public void hideButtons() {\r
781 \r
782                 undoButton.parentWidget().setVisible(false);\r
783                 buttonsVisible = false;\r
784         }\r
785 \r
786 \r
787         // Is the extended view on?\r
788         public boolean isExtended() {\r
789                 return extendedOn;\r
790         }\r
791 \r
792         // Listener for when a link is clicked\r
793         @SuppressWarnings("unused")\r
794         private void openFile() {\r
795                 logger.log(logger.EXTREME, "Starting openFile()");\r
796                 File fileHandle = new File(selectedFile);\r
797                 URI fileURL = fileHandle.toURI();\r
798                 String localURL = fileURL.toString();\r
799                 QUrl url = new QUrl(localURL);\r
800                 QFile file = new QFile(selectedFile);\r
801                 \r
802                 logger.log(logger.EXTREME, "Adding to fileWatcher:"+file.fileName());\r
803                 fileWatcher.addPath(file.fileName());\r
804         \r
805         if (!QDesktopServices.openUrl(url)) {\r
806                 logger.log(logger.LOW, "Error opening file :" +url);\r
807         }\r
808         }\r
809         \r
810         \r
811         // Listener for when a link is clicked\r
812         @SuppressWarnings("unused")\r
813         private void linkClicked(QUrl url) {\r
814                 logger.log(logger.EXTREME, "URL Clicked: " +url.toString());\r
815                 if (url.toString().substring(0,8).equals("nnres://")) {\r
816                         logger.log(logger.EXTREME, "URL is NN resource");\r
817                         if (url.toString().endsWith("/vnd.evernote.ink")) {\r
818                                 logger.log(logger.EXTREME, "Unable to open ink note");\r
819                                 QMessageBox.information(this, tr("Unable Open"), tr("This is an ink note.\n"+\r
820                                         "Ink notes are not supported since Evernote has not\n published any specifications on them\n" +\r
821                                         "and I'm too lazy to figure them out by myself."));\r
822                                 return;\r
823                         }\r
824                         String fullName = url.toString().substring(8);\r
825                         int index = fullName.indexOf(".");\r
826                         String guid = "";\r
827                         String type = "";\r
828                         if (index >-1) {\r
829                                 type = fullName.substring(index+1);\r
830                                 guid = fullName.substring(0,index);\r
831                         }\r
832                         index = guid.indexOf(Global.attachmentNameDelimeter);\r
833                         if (index > -1) {\r
834                                 guid = guid.substring(0,index);\r
835                         }\r
836                         List<Resource> resList = currentNote.getResources();\r
837                         Resource res = null;\r
838                         for (int i=0; i<resList.size(); i++) {\r
839                                 if (resList.get(i).getGuid().equals(guid)) {\r
840                                         res = resList.get(i);\r
841                                         i=resList.size();\r
842                                 }\r
843                         }\r
844                         if (res == null) {\r
845                                 String resGuid = Global.resourceMap.get(guid);\r
846                                 if (resGuid != null) \r
847                                         res = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid, true);\r
848                         }\r
849                         if (res != null) {\r
850                                 String fileName;\r
851                                 if (res.getAttributes() != null && \r
852                                                 res.getAttributes().getFileName() != null && \r
853                                                 !res.getAttributes().getFileName().trim().equals(""))\r
854                                         fileName = res.getGuid()+Global.attachmentNameDelimeter+res.getAttributes().getFileName();\r
855                                 else\r
856                                         fileName = res.getGuid()+"."+type;\r
857                                 QFile file = new QFile(Global.getFileManager().getResDirPath(fileName));\r
858                         QFile.OpenMode mode = new QFile.OpenMode();\r
859                         mode.set(QFile.OpenModeFlag.WriteOnly);\r
860                         boolean openResult = file.open(mode);\r
861                                 logger.log(logger.EXTREME, "File opened:" +openResult);\r
862                         QDataStream out = new QDataStream(file);\r
863                         Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(res.getGuid(), true);\r
864                                 QByteArray binData = new QByteArray(resBinary.getData().getBody());\r
865                                 resBinary = null;\r
866                                 logger.log(logger.EXTREME, "Writing resource");\r
867                         out.writeBytes(binData.toByteArray());\r
868                         file.close();\r
869                                 \r
870                         String whichOS = System.getProperty("os.name");\r
871                                 if (whichOS.contains("Windows")) \r
872                                 url.setUrl("file:///"+file.fileName());\r
873                         else\r
874                                 url.setUrl("file://"+file.fileName());\r
875                  //       fileWatcher.removePath(file.fileName());\r
876                                 logger.log(logger.EXTREME, "Adding file watcher " +file.fileName());\r
877                                 fileWatcher.addPath(file.fileName());\r
878                         \r
879                         // If we can't open it, then prompt the user to save it.\r
880                         if (!QDesktopServices.openUrl(url)) {\r
881                                         logger.log(logger.EXTREME, "We can't handle this.  Where do we put it?");\r
882                                 QFileDialog dialog = new QFileDialog();\r
883                                 dialog.show();\r
884                                 if (dialog.exec()!=0) {\r
885                                         List<String> fileNames = dialog.selectedFiles(); //gets all selected filenames\r
886                                         if (fileNames.size() == 0) \r
887                                                 return;\r
888                                         String sf = fileNames.get(0);\r
889                                         QFile saveFile = new QFile(sf);\r
890                                         mode.set(QFile.OpenModeFlag.WriteOnly);\r
891                                         saveFile.open(mode);\r
892                                         QDataStream saveOut = new QDataStream(saveFile);\r
893                                         saveOut.writeBytes(binData.toByteArray());\r
894                                         saveFile.close();\r
895                                         return;\r
896                                 }\r
897                                 }\r
898                         }\r
899                         return;\r
900                 }\r
901                 logger.log(logger.EXTREME, "Launching URL");\r
902                 QDesktopServices.openUrl(url);\r
903         }\r
904 \r
905         // Listener for when BOLD is clicked\r
906         @SuppressWarnings("unused")\r
907         private void undoClicked() {\r
908                 browser.page().triggerAction(WebAction.Undo);\r
909                 browser.setFocus();\r
910         }\r
911 \r
912         // Listener for when BOLD is clicked\r
913         @SuppressWarnings("unused")\r
914         private void redoClicked() {\r
915                 browser.page().triggerAction(WebAction.Redo);\r
916                 browser.setFocus();\r
917         }\r
918 \r
919         // Listener for when BOLD is clicked\r
920         @SuppressWarnings("unused")\r
921         private void boldClicked() {\r
922                 browser.page().triggerAction(WebAction.ToggleBold);\r
923                 microFocusChanged();\r
924                 browser.setFocus();\r
925         }\r
926 \r
927         // Listener for when Italics is clicked\r
928         @SuppressWarnings("unused")\r
929         private void italicClicked() {\r
930                 browser.page().triggerAction(WebAction.ToggleItalic);\r
931                 microFocusChanged();\r
932                 browser.setFocus();\r
933         }\r
934 \r
935         // Listener for when UNDERLINE is clicked\r
936         @SuppressWarnings("unused")\r
937         private void underlineClicked() {\r
938                 browser.page().triggerAction(WebAction.ToggleUnderline);\r
939                 microFocusChanged();\r
940                 browser.setFocus();\r
941         }\r
942 \r
943         // Listener for when Strikethrough is clicked\r
944         @SuppressWarnings("unused")\r
945         private void strikethroughClicked() {\r
946                 browser.page().mainFrame().evaluateJavaScript(\r
947                                 "document.execCommand('strikeThrough', false, '');");\r
948                 browser.setFocus();\r
949         }\r
950 \r
951         // Listener for when cut is clicked\r
952         @SuppressWarnings("unused")\r
953         private void cutClicked() {\r
954                 browser.page().triggerAction(WebAction.Cut);\r
955                 browser.setFocus();\r
956         }\r
957 \r
958         // Listener when COPY is clicked\r
959         @SuppressWarnings("unused")\r
960         private void copyClicked() {\r
961                 browser.page().triggerAction(WebAction.Copy);\r
962                 browser.setFocus();\r
963         }\r
964 \r
965         // Listener when PASTE is clicked\r
966         public void pasteClicked() {\r
967                 logger.log(logger.EXTREME, "Paste Clicked");\r
968                 if (forceTextPaste) {\r
969                         pasteWithoutFormattingClicked();\r
970                         return;\r
971                 }\r
972                 QClipboard clipboard = QApplication.clipboard();\r
973                 QMimeData mime = clipboard.mimeData();\r
974                 \r
975 //               String x = mime.html();\r
976 \r
977                 if (mime.hasImage()) {\r
978                         logger.log(logger.EXTREME, "Image paste found");\r
979                         insertImage(mime);\r
980                         browser.setFocus();\r
981                         return;\r
982                 }\r
983 \r
984                 if (mime.hasUrls()) {\r
985                         logger.log(logger.EXTREME, "URL paste found");\r
986                         handleUrls(mime);\r
987                         browser.setFocus();\r
988                         return;\r
989                 }\r
990                 \r
991                 String text = mime.html();\r
992                 if (text.contains("en-tag") && mime.hasHtml()) {\r
993                         logger.log(logger.EXTREME, "Intra-note paste found");\r
994                         text = fixInternotePaste(text);\r
995                         mime.setHtml(text);\r
996                         clipboard.setMimeData(mime);\r
997                 }\r
998 \r
999                 logger.log(logger.EXTREME, "Final paste choice encountered");\r
1000                 browser.page().triggerAction(WebAction.Paste);\r
1001                 browser.setFocus();\r
1002 \r
1003         }\r
1004 \r
1005         // Paste text without formatting\r
1006         private void pasteWithoutFormattingClicked() {\r
1007                 logger.log(logger.EXTREME, "Paste without format clipped");\r
1008                 QClipboard clipboard = QApplication.clipboard();\r
1009                 QMimeData mime = clipboard.mimeData();\r
1010                 if (!mime.hasText())\r
1011                         return;\r
1012                 String text = mime.text();\r
1013                 clipboard.setText(text);\r
1014                 browser.page().triggerAction(WebAction.Paste);\r
1015                 QApplication.clipboard().setMimeData(mime);\r
1016                 browser.setFocus();\r
1017 \r
1018         }\r
1019         \r
1020         // insert date/time\r
1021         @SuppressWarnings("unused")\r
1022         private void insertDateTime() {\r
1023                 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();\r
1024                 String dateTimeFormat = new String(fmt);\r
1025                 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);\r
1026                 Calendar cal = Calendar.getInstance();\r
1027                 \r
1028                 browser.page().mainFrame().evaluateJavaScript(\r
1029                         "document.execCommand('insertHtml', false, '"+simple.format(cal.getTime())+"');");\r
1030                 \r
1031                 browser.setFocus();\r
1032 \r
1033         }\r
1034 \r
1035         // Listener when Left is clicked\r
1036         @SuppressWarnings("unused")\r
1037         private void justifyLeftClicked() {\r
1038                 browser.page().mainFrame().evaluateJavaScript(\r
1039                                 "document.execCommand('JustifyLeft', false, '');");\r
1040                 browser.setFocus();\r
1041         }\r
1042 \r
1043         // Listener when Center is clicked\r
1044         @SuppressWarnings("unused")\r
1045         private void justifyCenterClicked() {\r
1046                 browser.page().mainFrame().evaluateJavaScript(\r
1047                                 "document.execCommand('JustifyCenter', false, '');");\r
1048                 browser.setFocus();\r
1049         }\r
1050 \r
1051         // Listener when Left is clicked\r
1052         @SuppressWarnings("unused")\r
1053         private void justifyRightClicked() {\r
1054                 browser.page().mainFrame().evaluateJavaScript(\r
1055                                 "document.execCommand('JustifyRight', false, '');");\r
1056                 browser.setFocus();\r
1057         }\r
1058 \r
1059         // Listener when HLINE is clicked\r
1060         @SuppressWarnings("unused")\r
1061         private void hlineClicked() {\r
1062                 browser.page().mainFrame().evaluateJavaScript(\r
1063                                 "document.execCommand('insertHorizontalRule', false, '');");\r
1064                 browser.setFocus();\r
1065         }\r
1066 \r
1067         // Listener when outdent is clicked\r
1068         private void outdentClicked() {\r
1069                 browser.page().mainFrame().evaluateJavaScript(\r
1070                                 "document.execCommand('outdent', false, '');");\r
1071                 browser.setFocus();\r
1072         }\r
1073 \r
1074         // Listener when a bullet list is clicked\r
1075         @SuppressWarnings("unused")\r
1076         private void bulletListClicked() {\r
1077                 browser.page().mainFrame().evaluateJavaScript(\r
1078                                 "document.execCommand('InsertUnorderedList', false, '');");\r
1079                 browser.setFocus();\r
1080         }\r
1081 \r
1082         // Listener when a bullet list is clicked\r
1083         @SuppressWarnings("unused")\r
1084         private void numberListClicked() {\r
1085                 browser.page().mainFrame().evaluateJavaScript(\r
1086                                 "document.execCommand('InsertOrderedList', false, '');");\r
1087                 browser.setFocus();\r
1088         }\r
1089 \r
1090         // Listener when indent is clicked\r
1091         private void indentClicked() {\r
1092                 browser.page().mainFrame().evaluateJavaScript(\r
1093                                 "document.execCommand('indent', false, '');");\r
1094                 browser.setFocus();\r
1095         }\r
1096 \r
1097         // Listener when the font name is changed\r
1098         @SuppressWarnings("unused")\r
1099         private void fontChanged(String font) {\r
1100                 browser.page().mainFrame().evaluateJavaScript(\r
1101                                 "document.execCommand('fontName',false,'" + font + "');");\r
1102                 browser.setFocus();\r
1103         }\r
1104 \r
1105         // Listener when a font size is changed\r
1106         @SuppressWarnings("unused")\r
1107         private void fontSizeChanged(String font) {\r
1108                 String text = browser.selectedText();\r
1109                 if (text.trim().equalsIgnoreCase(""))\r
1110                         return;\r
1111 \r
1112                 String selectedText = browser.selectedText();\r
1113                 String url = "<span style=\"font-size:" +font +"pt; \">"+selectedText +"</a>";\r
1114                 String script = "document.execCommand('insertHtml', false, '"+url+"');";\r
1115                 browser.page().mainFrame().evaluateJavaScript(script);\r
1116 /*              browser.page().mainFrame().evaluateJavaScript(\r
1117                                 "document.execCommand('fontSize',false,'"\r
1118                                                 + font + "');");\r
1119 */\r
1120                 browser.setFocus();\r
1121         }\r
1122 \r
1123         // Load the font combo box based upon the font selected\r
1124         private void loadFontSize(String name) {        \r
1125                 QFontDatabase db = new QFontDatabase(); \r
1126                 fontSize.clear();\r
1127                 List<Integer> points = db.pointSizes(name); \r
1128                 for (int i=0; i<points.size(); i++) { \r
1129                         fontSize.addItem(points.get(i).toString()); \r
1130                 }\r
1131                 /*\r
1132                 fontSize.addItem("x-small");\r
1133                 fontSize.addItem("small");\r
1134                 fontSize.addItem("medium");\r
1135                 fontSize.addItem("large");\r
1136                 fontSize.addItem("x-large");\r
1137                 fontSize.addItem("xx-large");\r
1138                 fontSize.addItem("xxx-large");\r
1139                 */\r
1140         }\r
1141 \r
1142         // Listener when a font size is changed\r
1143         @SuppressWarnings("unused")\r
1144         private void fontColorClicked() {\r
1145 //              QColorDialog dialog = new QColorDialog();\r
1146 //              QColor color = QColorDialog.getColor();\r
1147                 QColor color = fontColorMenu.getColor();\r
1148                 if (color.isValid())\r
1149                         browser.page().mainFrame().evaluateJavaScript(\r
1150                                         "document.execCommand('foreColor',false,'" + color.name()\r
1151                                                         + "');");\r
1152                 browser.setFocus();\r
1153         }\r
1154 \r
1155         // Listener for when a background color change is requested\r
1156         @SuppressWarnings("unused")\r
1157         private void fontHilightClicked() {\r
1158 //              QColorDialog dialog = new QColorDialog();\r
1159 //              QColor color = QColorDialog.getColor();\r
1160                 QColor color = fontHilightColorMenu.getColor();\r
1161                 if (color.isValid())\r
1162                         browser.page().mainFrame().evaluateJavaScript(\r
1163                                         "document.execCommand('backColor',false,'" + color.name()\r
1164                                                         + "');");\r
1165                 browser.setFocus();\r
1166         }\r
1167         \r
1168         // Listener for when a background color change is requested\r
1169         @SuppressWarnings("unused")\r
1170         private void superscriptClicked() {\r
1171                 browser.page().mainFrame().evaluateJavaScript(\r
1172                                         "document.execCommand('superscript');");\r
1173                 browser.setFocus();\r
1174         }\r
1175         \r
1176         // Listener for when a background color change is requested\r
1177         @SuppressWarnings("unused")\r
1178         private void subscriptClicked() {\r
1179                 browser.page().mainFrame().evaluateJavaScript(\r
1180                                         "document.execCommand('subscript');");\r
1181                 browser.setFocus();\r
1182         }\r
1183         // Insert a to-do checkbox\r
1184         @SuppressWarnings("unused")\r
1185         private void todoClicked() {\r
1186                 FileNameMap fileNameMap = URLConnection.getFileNameMap();\r
1187                 String script_start = new String(\r
1188                                 "document.execCommand('insertHtml', false, '");\r
1189                 String script_end = new String("');");\r
1190                 String todo = new String(\r
1191                                 "<input TYPE=\"CHECKBOX\" value=\"false\" onClick=\"value=checked; window.jambi.contentChanged(); \" />");\r
1192                 browser.page().mainFrame().evaluateJavaScript(\r
1193                                 script_start + todo + script_end);\r
1194                 browser.setFocus();\r
1195         }\r
1196 \r
1197         // Encrypt the selected text\r
1198         @SuppressWarnings("unused")\r
1199         private void encryptText() {\r
1200                 String text = browser.selectedText();\r
1201                 if (text.trim().equalsIgnoreCase(""))\r
1202                         return;\r
1203 \r
1204                 EnCryptDialog dialog = new EnCryptDialog();\r
1205                 dialog.exec();\r
1206                 if (!dialog.okPressed()) {\r
1207                         return;\r
1208                 }\r
1209 \r
1210                 EnCrypt crypt = new EnCrypt();\r
1211                 String encrypted = crypt.encrypt(text, dialog.getPassword().trim(), 64);\r
1212 \r
1213                 if (encrypted.trim().equals("")) {\r
1214                         QMessageBox.information(this, tr("Error"), tr("Error Encrypting String"));\r
1215                         return;\r
1216                 }\r
1217                 StringBuffer buffer = new StringBuffer(encrypted.length() + 100);\r
1218                 buffer.append("<img en-tag=\"en-crypt\" cipher=\"RC2\" hint=\""\r
1219                                 + dialog.getHint().replace("'","\\'") + "\" length=\"64\" ");\r
1220                 buffer.append("contentEditable=\"false\" alt=\"");\r
1221                 buffer.append(encrypted);\r
1222                 // NFC FIXME: should this be a file URL like in handleLocalAttachment and importAttachment?\r
1223                 buffer.append("\" src=\"").append(FileUtils.toForwardSlashedPath(Global.getFileManager().getImageDirPath("encrypt.png") +"\""));\r
1224                 Global.cryptCounter++;\r
1225                 buffer.append(" id=\"crypt"+Global.cryptCounter.toString() +"\"");\r
1226                 buffer.append(" onMouseOver=\"style.cursor=\\'hand\\'\"");\r
1227                 buffer.append(" onClick=\"window.jambi.decryptText(\\'crypt"+Global.cryptCounter.toString() \r
1228                                 +"\\', \\'"+encrypted+"\\', \\'"+dialog.getHint().replace("'", "\\&amp;apos;")+"\\');\"");\r
1229                 buffer.append("style=\"display:block\" />");\r
1230 \r
1231                 String script_start = new String(\r
1232                                 "document.execCommand('insertHtml', false, '");\r
1233                 String script_end = new String("');");\r
1234                 browser.page().mainFrame().evaluateJavaScript(\r
1235                                 script_start + buffer.toString() + script_end);\r
1236         }\r
1237 \r
1238         \r
1239         // Insert a hyperlink\r
1240         public void insertLink() {\r
1241                 logger.log(logger.EXTREME, "Inserting link");\r
1242                 String text = browser.selectedText();\r
1243                 if (text.trim().equalsIgnoreCase(""))\r
1244                         return;\r
1245 \r
1246                 InsertLinkDialog dialog = new InsertLinkDialog();\r
1247                 if (currentHyperlink != null && currentHyperlink != "") {\r
1248                         dialog.setUrl(currentHyperlink);\r
1249                 }\r
1250                 dialog.exec();\r
1251                 if (!dialog.okPressed()) {\r
1252                         logger.log(logger.EXTREME, "Insert link canceled");\r
1253                         return;\r
1254                 }\r
1255                 if (browser.insertLinkAction.text().equalsIgnoreCase("Insert Hyperlink")) {\r
1256                         String selectedText = browser.selectedText();\r
1257                         logger.log(logger.EXTREME, "Inserting link on text "+selectedText);\r
1258                         logger.log(logger.EXTREME, "URL Link " +dialog.getUrl().trim());\r
1259                         String dUrl = StringUtils.replace(dialog.getUrl().trim(), "'", "\\'");\r
1260                         String url = "<a href=\"" +dUrl\r
1261                                         +"\" title=" +dUrl \r
1262                                         +" >"+selectedText +"</a>";\r
1263                         String script = "document.execCommand('insertHtml', false, '"+url+"');";\r
1264                         browser.page().mainFrame().evaluateJavaScript(script);\r
1265                         return;\r
1266                 } else {\r
1267                         String js = new String( "function getCursorPos() {"\r
1268                                         +"var cursorPos;"\r
1269                                         +"if (window.getSelection) {"\r
1270                                         +"   var selObj = window.getSelection();"\r
1271                                         +"   var selRange = selObj.getRangeAt(0);"\r
1272                                         +"   var workingNode = window.getSelection().anchorNode.parentNode;"\r
1273                                         +"   while(workingNode != null) { " \r
1274                                         +"      if (workingNode.nodeName.toLowerCase()=='a') workingNode.setAttribute('href','" +dialog.getUrl() +"');"\r
1275                                         +"      workingNode = workingNode.parentNode;"\r
1276                                         +"   }"\r
1277                                         +"}"\r
1278                                         +"} getCursorPos();");\r
1279                                 browser.page().mainFrame().evaluateJavaScript(js);\r
1280                                 contentChanged();\r
1281                 }\r
1282                 \r
1283         }\r
1284         \r
1285         // Insert a table\r
1286         public void insertTable() {\r
1287                 TableDialog dialog = new TableDialog();\r
1288                 dialog.exec();\r
1289                 if (!dialog.okPressed()) {\r
1290                         return;\r
1291                 }\r
1292                 \r
1293                 int cols = dialog.getCols();\r
1294                 int rows = dialog.getRows();\r
1295                 int width = dialog.getWidth();\r
1296                 boolean percent = dialog.isPercent();\r
1297                 \r
1298                 String newHTML = "<table border=\"1\" width=\"" +new Integer(width).toString();\r
1299                 if (percent)\r
1300                         newHTML = newHTML +"%";\r
1301                 newHTML = newHTML + "\"><tbody>";\r
1302 \r
1303                 for (int i=0; i<rows; i++) {\r
1304                         newHTML = newHTML +"<tr>";\r
1305                         for (int j=0; j<cols; j++) {\r
1306                                 newHTML = newHTML +"<td>&nbsp;</td>";\r
1307                         }\r
1308                         newHTML = newHTML +"</tr>";\r
1309                 }\r
1310                 newHTML = newHTML+"</tbody></table>";   \r
1311         \r
1312                 String script = "document.execCommand('insertHtml', false, '"+newHTML+"');";\r
1313                 browser.page().mainFrame().evaluateJavaScript(script);\r
1314         }\r
1315         \r
1316         \r
1317         // Text content changed\r
1318         @SuppressWarnings("unused")\r
1319         private void selectionChanged() {\r
1320                 browser.encryptAction.setEnabled(true);\r
1321                 browser.insertLinkAction.setEnabled(true);\r
1322                 String scriptStart = "var selection_text = (window.getSelection()).toString();"\r
1323                                 + "var range = (window.getSelection()).getRangeAt(0);"\r
1324                                 + "var parent_html = range.commonAncestorContainer.innerHTML;"\r
1325                                 + "if (parent_html == undefined) {window.jambi.saveSelectedText(selection_text); return;}"\r
1326                                 + "var first_text = range.startContainer.nodeValue.substr(range.startOffset);"\r
1327                                 + "var last_text = (range.endContainer.nodeValue).substring(0,range.endOffset);"\r
1328                                 + "var start = parent_html.indexOf(first_text);"\r
1329                                 + "var end = parent_html.indexOf(last_text,start+1)+last_text.length;"\r
1330                                 + "var value = parent_html.substring(start,end);"\r
1331                                 + "window.jambi.saveSelectedText(value);" ;\r
1332                 browser.page().mainFrame().evaluateJavaScript(scriptStart);\r
1333 \r
1334         }\r
1335 \r
1336         public void saveSelectedText(String text) {\r
1337                 boolean enabled = true;\r
1338                 if (text.trim().length() == 0)\r
1339                         enabled=false;\r
1340                 if (text.indexOf("en-tag=\"en-crypt\"") >= 0)\r
1341                         enabled=false;\r
1342                 if (text.indexOf("<img en-tag=\"en-media\"") >= 0)\r
1343                         enabled=false;\r
1344                 if (text.indexOf("<a en-tag=\"en-media\"") >= 0)\r
1345                         enabled=false;\r
1346                 if (text.indexOf("<input ") >= 0)\r
1347                         enabled=false;\r
1348                 \r
1349                 browser.encryptAction.setEnabled(enabled);\r
1350                 browser.insertLinkAction.setEnabled(enabled);\r
1351 //              selectedText = text;\r
1352         }\r
1353 \r
1354         // Decrypt clicked text\r
1355         public void decryptText(String id, String text, String hint) {\r
1356                 EnCrypt crypt = new EnCrypt();\r
1357                 String plainText = null;\r
1358                 Calendar currentTime = new GregorianCalendar();\r
1359                 Long l = new Long(currentTime.getTimeInMillis());\r
1360                 String slot = new String(Long.toString(l));\r
1361                 \r
1362                 // First, try to decrypt with any keys we already have\r
1363                 for (int i=0; i<Global.passwordRemember.size(); i++) {\r
1364                         plainText = crypt.decrypt(text, Global.passwordRemember.get(i), 64);\r
1365                         if (plainText != null) {\r
1366                                 slot = new String(Long.toString(l));\r
1367                                 Global.passwordSafe.put(slot, Global.passwordRemember.get(i));\r
1368                                 removeEncryption(id, plainText, false, slot);   \r
1369                                 return;\r
1370                         }\r
1371                 }\r
1372                 \r
1373                 \r
1374                 EnDecryptDialog dialog = new EnDecryptDialog();\r
1375                 dialog.setHint(hint);\r
1376                 while (plainText == null || !dialog.okPressed()) {\r
1377                         dialog.exec();\r
1378                         if (!dialog.okPressed()) {\r
1379                                 return;\r
1380                         }\r
1381                         plainText = crypt.decrypt(text, dialog.getPassword().trim(), 64);\r
1382                         if (plainText == null) {\r
1383                                 QMessageBox.warning(this, "Incorrect Password", "The password entered is not correct");\r
1384                         }\r
1385                 }\r
1386                 Global.passwordSafe.put(slot, dialog.getPassword());\r
1387                 removeEncryption(id, plainText, dialog.permanentlyDecrypt(), slot);\r
1388                 if (dialog.rememberPassword())\r
1389                         Global.passwordRemember.add(dialog.getPassword());\r
1390 \r
1391         }\r
1392 \r
1393         // Get the editor tag line\r
1394         public TagLineEdit getTagLine() {\r
1395                 return tagEdit;\r
1396         }\r
1397 \r
1398         // Modify a note's tags\r
1399         @SuppressWarnings("unused")\r
1400         private void modifyTags() {\r
1401                 TagAssign tagWindow = new TagAssign(allTags, currentTags);\r
1402                 tagWindow.exec();\r
1403                 if (tagWindow.okClicked()) {\r
1404                         currentTags.clear();\r
1405                         StringBuffer tagDisplay = new StringBuffer();\r
1406 \r
1407                         List<QListWidgetItem> newTags = tagWindow.getTagList()\r
1408                                         .selectedItems();\r
1409                         for (int i = 0; i < newTags.size(); i++) {\r
1410                                 currentTags.add(newTags.get(i).text());\r
1411                                 tagDisplay.append(newTags.get(i).text());\r
1412                                 if (i < newTags.size() - 1) {\r
1413                                         tagDisplay.append(Global.tagDelimeter + " ");\r
1414                                 }\r
1415                         }\r
1416                         tagEdit.setText(tagDisplay.toString());\r
1417                         noteSignal.tagsChanged.emit(currentNote.getGuid(), currentTags);\r
1418                 }\r
1419         }\r
1420 \r
1421         // Tag line has been modified by typing text\r
1422         @SuppressWarnings("unused")\r
1423         private void modifyTagsTyping() {\r
1424                 String completionText = "";\r
1425                 if (tagEdit.currentCompleterSelection != null && !tagEdit.currentCompleterSelection.equals("")) {\r
1426                         completionText = tagEdit.currentCompleterSelection;\r
1427                         tagEdit.currentCompleterSelection = "";\r
1428                 }\r
1429                 \r
1430                 if (tagEdit.text().equalsIgnoreCase(saveTagList))\r
1431                         return;\r
1432 \r
1433                 // We know something has changed...\r
1434                 String oldTagArray[] = saveTagList.split(Global.tagDelimeter);\r
1435                 String newTagArray[] = tagEdit.text().split(Global.tagDelimeter);\r
1436                 \r
1437                 if (!completionText.equals("") && newTagArray.length > 0) {\r
1438                         newTagArray[newTagArray.length-1] = completionText;\r
1439                 }\r
1440                 // Remove any potential duplicates from the new list\r
1441                 for (int i=0; i<newTagArray.length; i++) {\r
1442                         boolean foundOnce = false;\r
1443                         for (int j=0; j<newTagArray.length; j++) {\r
1444                                 if (newTagArray[j].equalsIgnoreCase(newTagArray[i])) {\r
1445                                         if (!foundOnce) {\r
1446                                                 foundOnce = true;\r
1447                                         } else\r
1448                                                 newTagArray[j] = "";\r
1449                                 }\r
1450                         }\r
1451                 }\r
1452 \r
1453                 List<String> newTagList = new ArrayList<String>();\r
1454                 List<String> oldTagList = new ArrayList<String>();\r
1455 \r
1456                 for (int i = 0; i < oldTagArray.length; i++)\r
1457                         if (!oldTagArray[i].trim().equals(""))\r
1458                                 oldTagList.add(oldTagArray[i]);\r
1459                 for (int i = 0; i < newTagArray.length; i++)\r
1460                         if (!newTagArray[i].trim().equals(""))\r
1461                                 newTagList.add(newTagArray[i]);\r
1462 \r
1463                 // Let's cleanup the appearance of the tag list\r
1464                 Collections.sort(newTagList);\r
1465                 String newDisplay = "";\r
1466                 for (int i=0; i<newTagList.size(); i++) {\r
1467                         newDisplay = newDisplay+newTagList.get(i);\r
1468                         if (i<newTagList.size()-1)\r
1469                                 newDisplay = newDisplay+", ";\r
1470                 }\r
1471                 tagEdit.blockSignals(true);\r
1472                 tagEdit.setText(newDisplay);\r
1473                 tagEdit.blockSignals(false);\r
1474                 \r
1475                 // We now have lists of the new & old. Remove duplicates. If all\r
1476                 // are removed from both then nothing has really changed\r
1477                 for (int i = newTagList.size() - 1; i >= 0; i--) {\r
1478                         String nTag = newTagList.get(i);\r
1479                         for (int j = oldTagList.size() - 1; j >= 0; j--) {\r
1480                                 String oTag = oldTagList.get(j);\r
1481                                 if (oTag.equalsIgnoreCase(nTag)) {\r
1482                                         oldTagList.remove(j);\r
1483                                         newTagList.remove(i);\r
1484                                         j = -1;\r
1485                                 }\r
1486                         }\r
1487                 }\r
1488 \r
1489                 if (oldTagList.size() != 0 || newTagList.size() != 0) {\r
1490                         currentTags.clear();\r
1491                         newTagArray = tagEdit.text().split(Global.tagDelimeter);\r
1492                         for (int i = 0; i < newTagArray.length; i++)\r
1493                                 if (!newTagArray[i].trim().equals(""))\r
1494                                         currentTags.add(newTagArray[i].trim());\r
1495 \r
1496                         noteSignal.tagsChanged.emit(currentNote.getGuid(), currentTags);\r
1497                 }\r
1498                 \r
1499         }\r
1500 \r
1501         // Tab button was pressed\r
1502         public void tabPressed() {\r
1503                 if (!insideList) {\r
1504                         String script_start = new String(\r
1505                         "document.execCommand('insertHtml', false, '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');");\r
1506                         browser.page().mainFrame().evaluateJavaScript(script_start);\r
1507                 } else \r
1508                         indentClicked();\r
1509         }\r
1510         \r
1511         public void backtabPressed() {\r
1512                 if (insideList)\r
1513                         outdentClicked();\r
1514         }\r
1515         \r
1516         public void setInsideList() {\r
1517                 insideList = true;\r
1518         }\r
1519         \r
1520         // The title has been edited\r
1521         @SuppressWarnings("unused")\r
1522         private void titleEdited() {\r
1523                 // If we don't have a good note, or if the current title\r
1524                 // matches the old title then we don't need to do anything\r
1525                 if (currentNote == null)\r
1526                         return;\r
1527                 if (currentNote.getTitle().trim().equals(titleLabel.text().trim()))\r
1528                         return;\r
1529                 \r
1530                 // If we have a real change, we need to save it.\r
1531                 noteSignal.titleChanged.emit(currentNote.getGuid(), titleLabel.text());\r
1532                 currentNote.setTitle(titleLabel.text());\r
1533                 saveNoteTitle = titleLabel.text();\r
1534                 checkNoteTitle();\r
1535         }\r
1536 \r
1537         // Set the list of note tags\r
1538         public void setAllTags(List<Tag> l) {\r
1539                 allTags = l;\r
1540                 tagEdit.setTagList(l);\r
1541         }\r
1542 \r
1543         // Setter for the current tags\r
1544         public void setCurrentTags(List<String> s) {\r
1545                 currentTags = s;\r
1546         }\r
1547 \r
1548         // Save the list of notebooks\r
1549         public void setNotebookList(List<Notebook> n) {\r
1550                 notebookList = n;\r
1551                 loadNotebookList();\r
1552         }\r
1553 \r
1554         // Load the notebook list and select the current notebook\r
1555         private void loadNotebookList() {\r
1556                 if (notebookBox.count() != 0)\r
1557                         notebookBox.clear();\r
1558                 if (notebookList == null)\r
1559                         return;\r
1560 \r
1561                 for (int i = 0; i < notebookList.size(); i++) {\r
1562                         notebookBox.addItem(notebookList.get(i).getName());\r
1563                         if (currentNote != null) {\r
1564                                 if (currentNote.getNotebookGuid().equals(\r
1565                                                 notebookList.get(i).getGuid())) {\r
1566                                         notebookBox.setCurrentIndex(i);\r
1567                                 }\r
1568                         }\r
1569                 }\r
1570         }\r
1571 \r
1572         // Get the contents of the editor\r
1573         public String getContent() {\r
1574                 return browser.page().currentFrame().toHtml();\r
1575         }\r
1576 \r
1577         // The note contents have changed\r
1578         public void contentChanged() {\r
1579                 String content = getContent();\r
1580                 checkNoteTitle();\r
1581                 noteSignal.noteChanged.emit(currentNote.getGuid(), content); \r
1582         }\r
1583 \r
1584         // The notebook selection has changed\r
1585         @SuppressWarnings("unused")\r
1586         private void notebookChanged() {\r
1587                 boolean changed = false;\r
1588                 String n = notebookBox.currentText();\r
1589                 for (int i = 0; i < notebookList.size(); i++) {\r
1590                         if (n.equals(notebookList.get(i).getName())) {\r
1591                                 if (!notebookList.get(i).getGuid().equals(currentNote.getNotebookGuid())) {\r
1592                                         currentNote.setNotebookGuid(notebookList.get(i).getGuid());\r
1593                                         changed = true;\r
1594                                 }\r
1595                                 i = notebookList.size();\r
1596                         }\r
1597                 }\r
1598                 \r
1599                 // If the notebook changed, signal the update\r
1600                 if (changed)\r
1601                         noteSignal.notebookChanged.emit(currentNote.getGuid(), currentNote\r
1602                                         .getNotebookGuid());\r
1603         }\r
1604 \r
1605         // Check the note title\r
1606         private void checkNoteTitle() {\r
1607                 String text = browser.page().currentFrame().toPlainText();\r
1608                 if (saveNoteTitle.trim().equals("") || saveNoteTitle.trim().equals("Untitled Note")) {\r
1609                         int newLine = text.indexOf("\n");\r
1610                         if (newLine > 0) {\r
1611                                 text = text.substring(0, newLine);\r
1612                                 if (text.trim().equals(""))\r
1613                                         text = tr("Untitled Note");\r
1614                                 titleLabel.setText(text);\r
1615                         } else {\r
1616                                 if (text.length() > Constants.EDAM_NOTE_TITLE_LEN_MAX)\r
1617                                         titleLabel.setText(text.substring(0, Constants.EDAM_NOTE_TITLE_LEN_MAX));\r
1618                                 else {\r
1619                                         titleLabel.blockSignals(true);\r
1620                                         if (text.trim().equals(""))\r
1621                                                 titleLabel.setText(tr("Untitled Note"));\r
1622                                         else\r
1623                                                 titleLabel.setText(text);\r
1624                                         titleLabel.blockSignals(false);\r
1625                                 }\r
1626                         }\r
1627                         noteSignal.titleChanged.emit(currentNote.getGuid(), titleLabel\r
1628                                         .text());\r
1629                 }\r
1630         }\r
1631 \r
1632         // Return the note contents so we can email them\r
1633         public String getContentsToEmail() {\r
1634                 return browser.page().currentFrame().toPlainText().trim();\r
1635                 /*\r
1636                  * int body = browser.page().currentFrame().toHtml().indexOf("<body>");\r
1637                  * String temp = browser.page().currentFrame().toHtml(); if (body == -1)\r
1638                  * temp = "<html><body><b>Test</b></body></html>"; else temp =\r
1639                  * "<html>"+temp.substring(body); return temp; // return\r
1640                  * urlEncode(browser.page().currentFrame().toHtml());\r
1641                  */\r
1642         }\r
1643 \r
1644         // Insert an image into the editor\r
1645         private void insertImage(QMimeData mime) {\r
1646                 logger.log(logger.EXTREME, "Entering insertImage");\r
1647                 QImage img = (QImage) mime.imageData();\r
1648                 String script_start = new String(\r
1649                                 "document.execCommand('insertHTML', false, '");\r
1650                 String script_end = new String("');");\r
1651 \r
1652                 long now = new Date().getTime();\r
1653                 String path = Global.getFileManager().getResDirPath(\r
1654                                 (new Long(now).toString()) + ".jpg");\r
1655 \r
1656                 // This block is just a hack to make sure we wait at least 1ms so we\r
1657                 // don't\r
1658                 // have collisions on image names\r
1659                 long i = new Date().getTime();\r
1660                 while (now == i)\r
1661                         i = new Date().getTime();\r
1662 \r
1663                 // Open the file & write the data\r
1664                 QFile tfile = new QFile(path);\r
1665                 tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly));\r
1666                 img.save(tfile);\r
1667                 tfile.close();\r
1668                 \r
1669                 Resource newRes = createResource(QUrl.fromLocalFile(path).toString(), 0, "image/jpeg", false);\r
1670                 if (newRes == null)\r
1671                         return;\r
1672                 currentNote.getResources().add(newRes);\r
1673 \r
1674                 // do the actual insert into the note\r
1675                 StringBuffer buffer = new StringBuffer(100);\r
1676                 buffer.append("<img src=\"");\r
1677                 buffer.append(tfile.fileName());\r
1678                 buffer.append("\" en-tag=en-media type=\"image/jpeg\""\r
1679                                 +" hash=\""+Global.byteArrayToHexString(newRes.getData().getBodyHash()) +"\""\r
1680                                 +" guid=\"" +newRes.getGuid() +"\""\r
1681 //                              +" onContextMenu=\"window.jambi.imageContextMenu('" +tfile.fileName() +"');\""\r
1682                                 +" onContextMenu=\"window.jambi.imageContextMenu(&amp." +tfile.fileName() +"&amp.);\""\r
1683                                 + " />");\r
1684                 \r
1685                 browser.page().mainFrame().evaluateJavaScript(\r
1686                                 script_start + buffer + script_end);\r
1687 \r
1688                 return;\r
1689         }\r
1690 \r
1691         // Handle URLs that are trying to be pasted\r
1692         public void handleUrls(QMimeData mime) {\r
1693                 logger.log(logger.EXTREME, "Starting handleUrls");\r
1694                 FileNameMap fileNameMap = URLConnection.getFileNameMap();\r
1695 \r
1696                 List<QUrl> urlList = mime.urls();\r
1697                 String url = new String();\r
1698                 String script_start = new String(\r
1699                                 "document.execCommand('createLink', false, '");\r
1700                 String script_end = new String("');");\r
1701 \r
1702                 for (int i = 0; i < urlList.size(); i++) {\r
1703                         url = urlList.get(i).toString();\r
1704                         // Find out what type of file we have\r
1705                         String mimeType = fileNameMap.getContentTypeFor(url);\r
1706 \r
1707                         // If null returned, we need to guess at the file type\r
1708                         if (mimeType == null)\r
1709                                 mimeType = "application/"\r
1710                                                 + url.substring(url.lastIndexOf(".") + 1);\r
1711 \r
1712                         // Check if we have an image or some other type of file\r
1713                         if (url.substring(0, 5).equalsIgnoreCase("file:")\r
1714                                         && mimeType.substring(0, 5).equalsIgnoreCase("image")) {\r
1715                                 handleLocalImageURLPaste(mime, mimeType);\r
1716                                 return;\r
1717                         }\r
1718                         String[] type = mimeType.split("/");\r
1719                         boolean valid = validAttachment(type[1]);\r
1720                         boolean smallEnough = checkFileAttachmentSize(url);\r
1721                         if (smallEnough && valid\r
1722                                         && url.substring(0, 5).equalsIgnoreCase("file:")\r
1723                                         && !mimeType.substring(0, 5).equalsIgnoreCase("image")) {\r
1724                                 handleLocalAttachment(mime, mimeType);\r
1725                                 return;\r
1726                         }\r
1727                         browser.page().mainFrame().evaluateJavaScript(\r
1728                                         script_start + url + script_end);\r
1729                 }\r
1730                 return;\r
1731         }\r
1732 \r
1733         // If a URL being pasted is an image URL, then attach the image\r
1734         private void handleLocalImageURLPaste(QMimeData mime, String mimeType) {\r
1735                 List<QUrl> urlList = mime.urls();\r
1736                 String url = new String();\r
1737                 String script_start_image = new String(\r
1738                                 "document.execCommand('insertHtml', false, '");\r
1739                 String script_end = new String("');");\r
1740                 StringBuffer buffer;\r
1741 \r
1742                 // Copy the image over into the resource directory and create a new resource \r
1743                 // record for each url pasted\r
1744                 for (int i = 0; i < urlList.size(); i++) {\r
1745                         url = urlList.get(i).toString();\r
1746 \r
1747                         Resource newRes = createResource(url, i, mimeType, false);\r
1748                         if (newRes == null)\r
1749                                 return;\r
1750                         currentNote.getResources().add(newRes);\r
1751                         buffer = new StringBuffer(100);\r
1752                         \r
1753                         // Open the file & write the data\r
1754                         String fileName = Global.getFileManager().getResDirPath(newRes.getGuid());\r
1755                         QFile tfile = new QFile(fileName);\r
1756                         tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly));\r
1757                         tfile.write(newRes.getData().getBody());\r
1758                         tfile.close();\r
1759                         buffer.append(script_start_image);\r
1760                         buffer.append("<img src=\"" + FileUtils.toForwardSlashedPath(fileName));\r
1761 //                      if (mimeType.equalsIgnoreCase("image/jpg"))\r
1762 //                              mimeType = "image/jpeg";\r
1763                         buffer.append("\" en-tag=\"en-media\" type=\"" + mimeType +"\""\r
1764                                         +" hash=\""+Global.byteArrayToHexString(newRes.getData().getBodyHash()) +"\""\r
1765                                         +" guid=\"" +newRes.getGuid() +"\""\r
1766                                         +" onContextMenu=\"window.jambi.imageContextMenu(&apos;" +tfile.fileName() +"&apos;);\""\r
1767                                         + " />");\r
1768                         buffer.append(script_end);\r
1769                         browser.page().mainFrame().evaluateJavaScript(buffer.toString());\r
1770                 }\r
1771                 return;\r
1772         }\r
1773         \r
1774 \r
1775         // If a URL being pasted is a local file URL, then attach the file\r
1776         private void handleLocalAttachment(QMimeData mime, String mimeType) {\r
1777                 logger.log(logger.EXTREME, "Attaching local file");\r
1778                 List<QUrl> urlList = mime.urls();\r
1779                 String script_start = new String(\r
1780                                 "document.execCommand('insertHtml', false, '");\r
1781                 String script_end = new String("');");\r
1782                 StringBuffer buffer;\r
1783 \r
1784                         String[] type = mimeType.split("/");\r
1785                         String icon = findIcon(type[1]);\r
1786                         if (icon.equals("attachment.png"))\r
1787                                 icon = findIcon(type[0]);\r
1788                         buffer = new StringBuffer(100);\r
1789 \r
1790                 for (int i = 0; i < urlList.size(); i++) {\r
1791                         String url = urlList.get(i).toString();\r
1792 \r
1793                         // Start building the HTML\r
1794                         if (icon.equals("attachment.png"))\r
1795                                 icon = findIcon(url.substring(url.lastIndexOf(".")+1));\r
1796                         String imageURL = FileUtils.toFileURLString(Global.getFileManager().getImageDirFile(icon));\r
1797 \r
1798                         logger.log(logger.EXTREME, "Creating resource ");\r
1799                         Resource newRes = createResource(url, i, mimeType, true);\r
1800                         if (newRes == null)\r
1801                                 return;\r
1802                         logger.log(logger.EXTREME, "New resource size: " +newRes.getData().getSize());\r
1803                         currentNote.getResources().add(newRes);\r
1804                         \r
1805                         String fileName = newRes.getGuid() + Global.attachmentNameDelimeter+newRes.getAttributes().getFileName();\r
1806                         // If we have a PDF, we need to setup the preview.\r
1807                         if (icon.equalsIgnoreCase("pdf.png") && Global.pdfPreview()) {\r
1808                                 logger.log(logger.EXTREME, "Setting up PDF preview");\r
1809                                 if (newRes.getAttributes() != null && \r
1810                                                 newRes.getAttributes().getFileName() != null && \r
1811                                                 !newRes.getAttributes().getFileName().trim().equals(""))\r
1812                                         fileName = newRes.getGuid()+Global.attachmentNameDelimeter+\r
1813                                                 newRes.getAttributes().getFileName();\r
1814                                 else\r
1815                                         fileName = newRes.getGuid()+".pdf";\r
1816                                 QFile file = new QFile(Global.getFileManager().getResDirPath(fileName));\r
1817                         QFile.OpenMode mode = new QFile.OpenMode();\r
1818                         mode.set(QFile.OpenModeFlag.WriteOnly);\r
1819                         file.open(mode);\r
1820                         QDataStream out = new QDataStream(file);\r
1821 //                      Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(newRes.getGuid(), true);\r
1822                                 QByteArray binData = new QByteArray(newRes.getData().getBody());\r
1823 //                              resBinary = null;\r
1824                         out.writeBytes(binData.toByteArray());\r
1825                         file.close();\r
1826 \r
1827                                 PDFPreview pdfPreview = new PDFPreview();\r
1828                                 if (pdfPreview.setupPreview(Global.getFileManager().getResDirPath(fileName), "pdf",0)) {\r
1829                                 // NFC TODO: should this be a 'file://' url like the ones above?\r
1830                                 imageURL = file.fileName() + ".png";\r
1831                                 }\r
1832                         }\r
1833                                                 \r
1834                         logger.log(logger.EXTREME, "Generating link tags");\r
1835                         buffer.delete(0, buffer.length());\r
1836                         buffer.append("<a en-tag=\"en-media\" guid=\"" +newRes.getGuid()+"\" ");\r
1837                         buffer.append(" onContextMenu=\"window.jambi.imageContextMenu(&apos;")\r
1838                       .append(Global.getFileManager().getResDirPath(fileName))\r
1839                       .append("&apos;);\" ");                   buffer.append("type=\"" + mimeType + "\" href=\"nnres://" + fileName +"\" hash=\""+Global.byteArrayToHexString(newRes.getData().getBodyHash()) +"\" >");\r
1840                         buffer.append("<img src=\"" + imageURL + "\" title=\"" +newRes.getAttributes().getFileName());\r
1841                         buffer.append("\"></img>");\r
1842                         buffer.append("</a>");\r
1843                         browser.page().mainFrame().evaluateJavaScript(\r
1844                                         script_start + buffer.toString() + script_end);\r
1845                 }\r
1846                 return;\r
1847         }\r
1848 \r
1849         private Resource createResource(String url, int sequence, String mime, boolean attachment) {\r
1850                 logger.log(logger.EXTREME, "Inside create resource");\r
1851                 QFile resourceFile;\r
1852                 String urlTest = new QUrl(url).toLocalFile();\r
1853                 if (!urlTest.equals(""))\r
1854                         url = urlTest;\r
1855                 url = url.replace("/", File.separator);\r
1856         resourceFile = new QFile(url); \r
1857         resourceFile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly));\r
1858         byte[] fileData = resourceFile.readAll().toByteArray();\r
1859         resourceFile.close();\r
1860         if (fileData.length == 0)\r
1861                 return null;\r
1862         MessageDigest md;\r
1863         try {\r
1864                 md = MessageDigest.getInstance("MD5");\r
1865                 md.update(fileData);\r
1866                 byte[] hash = md.digest();\r
1867   \r
1868                 Resource r = new Resource();\r
1869                 Calendar time = new GregorianCalendar();\r
1870                 long prevTime = time.getTimeInMillis();\r
1871                 while (prevTime == time.getTimeInMillis()) {\r
1872                         time = new GregorianCalendar();\r
1873                 }\r
1874                 r.setGuid(time.getTimeInMillis()+new Integer(sequence).toString());\r
1875                 r.setNoteGuid(currentNote.getGuid());\r
1876                 r.setMime(mime);\r
1877                 r.setActive(true);\r
1878                 r.setUpdateSequenceNum(0);\r
1879                 r.setWidth((short) 0);\r
1880                 r.setHeight((short) 0);\r
1881                 r.setDuration((short) 0);\r
1882                                 \r
1883                 Data d = new Data();\r
1884                 d.setBody(fileData);\r
1885                 d.setBodyIsSet(true);\r
1886                 d.setBodyHash(hash);\r
1887                 d.setBodyHashIsSet(true);\r
1888                 r.setData(d);\r
1889                 d.setSize(fileData.length);\r
1890                 \r
1891                 int fileNamePos = url.lastIndexOf(File.separator);\r
1892                 if (fileNamePos == -1)\r
1893                         fileNamePos = url.lastIndexOf("/");\r
1894                         String fileName = url.substring(fileNamePos+1);\r
1895                 ResourceAttributes a = new ResourceAttributes();\r
1896                 a.setAltitude(0);\r
1897                 a.setAltitudeIsSet(false);\r
1898                 a.setLongitude(0);\r
1899                 a.setLongitudeIsSet(false);\r
1900                 a.setLatitude(0);\r
1901                 a.setLatitudeIsSet(false);\r
1902                 a.setCameraMake("");\r
1903                 a.setCameraMakeIsSet(false);\r
1904                 a.setCameraModel("");\r
1905                 a.setCameraModelIsSet(false);\r
1906                 a.setAttachment(attachment);\r
1907                 a.setAttachmentIsSet(true);\r
1908                 a.setClientWillIndex(false);\r
1909                 a.setClientWillIndexIsSet(true);\r
1910                 a.setRecoType("");\r
1911                 a.setRecoTypeIsSet(false);\r
1912                 a.setSourceURL(url);\r
1913                 a.setSourceURLIsSet(true);\r
1914                 a.setTimestamp(0);\r
1915                 a.setTimestampIsSet(false);\r
1916                 a.setFileName(fileName);\r
1917                 a.setFileNameIsSet(true);\r
1918                 r.setAttributes(a);\r
1919                 \r
1920                 conn.getNoteTable().noteResourceTable.saveNoteResource(r, true);\r
1921                 return r;\r
1922         } catch (NoSuchAlgorithmException e1) {\r
1923                 e1.printStackTrace();\r
1924                 }\r
1925         return null;\r
1926         }\r
1927         \r
1928 \r
1929     // find the appropriate icon for an attachment\r
1930     private String findIcon(String appl) {\r
1931         appl = appl.toLowerCase();\r
1932         File f = Global.getFileManager().getImageDirFile(appl + ".png");\r
1933         if (f.exists())\r
1934                 return appl+".png";\r
1935         return "attachment.png";\r
1936     }\r
1937 \r
1938         // Check if the account supports this type of attachment\r
1939         private boolean validAttachment(String type) {\r
1940                 if (Global.isPremium())\r
1941                         return true;\r
1942                 if (type.equalsIgnoreCase("JPG"))\r
1943                         return true;\r
1944                 if (type.equalsIgnoreCase("PNG"))\r
1945                         return true;\r
1946                 if (type.equalsIgnoreCase("GIF"))\r
1947                         return true;\r
1948                 if (type.equalsIgnoreCase("MP3"))\r
1949                         return true;\r
1950                 if (type.equalsIgnoreCase("WAV"))\r
1951                         return true;\r
1952                 if (type.equalsIgnoreCase("AMR"))\r
1953                         return true;\r
1954                 if (type.equalsIgnoreCase("PDF"))\r
1955                         return true;\r
1956                 String error = tr("Non-premium accounts can only attach JPG, PNG, GIF, MP3, WAV, AMR, or PDF files.");\r
1957                 QMessageBox.information(this, tr("Non-Premium Account"), error);\r
1958 \r
1959                 return false;\r
1960         }\r
1961 \r
1962         // Check the file attachment to be sure it isn't over 25 mb\r
1963         private boolean checkFileAttachmentSize(String url) {\r
1964                 String fileName = url.substring(8);\r
1965                 QFile resourceFile = new QFile(fileName);\r
1966                 resourceFile.open(new QIODevice.OpenMode(\r
1967                                 QIODevice.OpenModeFlag.ReadOnly));\r
1968                 long size = resourceFile.size();\r
1969                 resourceFile.close();\r
1970                 size = size / 1024 / 1024;\r
1971                 if (size < 50 && Global.isPremium())\r
1972                         return true;\r
1973                 if (size < 25)\r
1974                         return true;\r
1975 \r
1976                 String error = tr("A file attachment may not exceed 25MB.");\r
1977                 QMessageBox.information(this, tr("Attachment Size"), error);\r
1978                 return false;\r
1979         }\r
1980 \r
1981 \r
1982         @SuppressWarnings("unused")\r
1983         private void createdChanged() {\r
1984                 QDateTime dt = new QDateTime();\r
1985                 dt.setDate(createdDate.date());\r
1986                 dt.setTime(createdTime.time());\r
1987                 noteSignal.createdDateChanged.emit(currentNote.getGuid(), dt);\r
1988 \r
1989         }\r
1990 \r
1991         @SuppressWarnings("unused")\r
1992         private void alteredChanged() {\r
1993                 QDateTime dt = new QDateTime();\r
1994                 dt.setDate(alteredDate.date());\r
1995                 dt.setTime(alteredTime.time());\r
1996                 noteSignal.alteredDateChanged.emit(currentNote.getGuid(), dt);\r
1997         }\r
1998 \r
1999         @SuppressWarnings("unused")\r
2000         private void subjectDateTimeChanged() {\r
2001                 QDateTime dt = new QDateTime();\r
2002                 dt.setDate(subjectDate.date());\r
2003                 dt.setTime(subjectTime.time());\r
2004                 noteSignal.subjectDateChanged.emit(currentNote.getGuid(), dt);\r
2005 \r
2006         }\r
2007 \r
2008         @SuppressWarnings("unused")\r
2009         private void sourceUrlChanged() {\r
2010                 noteSignal.sourceUrlChanged.emit(currentNote.getGuid(), urlText.text());\r
2011         }\r
2012 \r
2013         @SuppressWarnings("unused")\r
2014         private void authorChanged() {\r
2015                 noteSignal.authorChanged.emit(currentNote.getGuid(), authorText.text());\r
2016         }\r
2017         \r
2018         @SuppressWarnings("unused")\r
2019         private void geoBoxChanged() {\r
2020                 int index = geoBox.currentIndex();\r
2021                 geoBox.setCurrentIndex(0);\r
2022                 if (index == 1) {\r
2023                         GeoDialog box = new GeoDialog();\r
2024                         box.setLongitude(currentNote.getAttributes().getLongitude());\r
2025                         box.setLatitude(currentNote.getAttributes().getLatitude());\r
2026                         box.setAltitude(currentNote.getAttributes().getAltitude());\r
2027                         box.exec();\r
2028                         if (!box.okPressed())\r
2029                                 return;\r
2030                         double alt = box.getAltitude();\r
2031                         double lat = box.getLatitude();\r
2032                         double lon = box.getLongitude();\r
2033                         if (alt != currentNote.getAttributes().getAltitude() ||\r
2034                                 lon != currentNote.getAttributes().getLongitude() ||\r
2035                                 lat != currentNote.getAttributes().getLatitude()) {\r
2036                                         noteSignal.geoChanged.emit(currentNote.getGuid(), lon, lat, alt);\r
2037                                         currentNote.getAttributes().setAltitude(alt);\r
2038                                         currentNote.getAttributes().setLongitude(lon);\r
2039                                         currentNote.getAttributes().setLatitude(lat);\r
2040                         }\r
2041                 }\r
2042                 \r
2043                 if (index == 2) {\r
2044                         noteSignal.geoChanged.emit(currentNote.getGuid(), 0.0, 0.0, 0.0);\r
2045                         currentNote.getAttributes().setAltitude(0.0);\r
2046                         currentNote.getAttributes().setLongitude(0.0);\r
2047                         currentNote.getAttributes().setLatitude(0.0);\r
2048                 }\r
2049                 \r
2050                 if (index == 3 || index == 0) {\r
2051                         QDesktopServices.openUrl(new QUrl("http://maps.google.com/maps?z=6&q="+currentNote.getAttributes().getLatitude() +"," +currentNote.getAttributes().getLongitude()));\r
2052                 }\r
2053         }\r
2054 \r
2055         // ************************************************************\r
2056         // * User chose to save an attachment. Pares out the request *\r
2057         // * into a guid & file. Save the result. *\r
2058         // ************************************************************\r
2059         public void downloadAttachment(QNetworkRequest request) {\r
2060                 String guid;\r
2061                 QFileDialog fd = new QFileDialog(this);\r
2062                 fd.setFileMode(FileMode.AnyFile);\r
2063                 fd.setConfirmOverwrite(true);\r
2064                 fd.setWindowTitle(tr("Save File"));\r
2065                 fd.setAcceptMode(AcceptMode.AcceptSave);\r
2066                 fd.setDirectory(System.getProperty("user.home"));\r
2067                 String name = request.url().toString();\r
2068 \r
2069                 int pos = name.lastIndexOf(Global.attachmentNameDelimeter);\r
2070                 if (pos > -1) {\r
2071                         guid = name.substring(0, pos).replace("nnres://", "");\r
2072                         name = name.substring(pos +Global.attachmentNameDelimeter.length());\r
2073                         fd.selectFile(name);\r
2074                         pos = name.lastIndexOf('.');\r
2075                         if (pos > -1) {\r
2076                                 String mimeType = "(*." + name.substring(pos + 1)\r
2077                                                 + ");; All Files (*)";\r
2078                                 fd.setFilter(tr(mimeType));\r
2079                         }\r
2080                 } else {\r
2081                         guid = name;\r
2082                 }\r
2083 \r
2084                 // Strip URL prefix and base dir\r
2085                 guid = guid.replace("nnres://", "")\r
2086                         .replace(FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath()), "");\r
2087 \r
2088                 pos = guid.lastIndexOf('.');\r
2089                 if (pos > 0)\r
2090                         guid = guid.substring(0,pos);\r
2091                 if (fd.exec() != 0 && fd.selectedFiles().size() > 0) {\r
2092                         name = name.replace('\\', '/');\r
2093                         Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);\r
2094                         QFile saveFile = new QFile(fd.selectedFiles().get(0));\r
2095                         QFile.OpenMode mode = new QFile.OpenMode();\r
2096                         mode.set(QFile.OpenModeFlag.WriteOnly);\r
2097                         saveFile.open(mode);\r
2098                         QDataStream saveOut = new QDataStream(saveFile);\r
2099                         QByteArray binData = new QByteArray(resBinary.getData().getBody());\r
2100                         saveOut.writeBytes(binData.toByteArray());\r
2101                         saveFile.close();\r
2102 \r
2103                 }\r
2104         }\r
2105 \r
2106         \r
2107         // ************************************************************\r
2108         // * User chose to save an attachment. Pares out the request *\r
2109         // * into a guid & file. Save the result. --- DONE FROM downloadAttachment now!!!!!   \r
2110         // ************************************************************\r
2111         // NFC TODO: unused? remove\r
2112         public void downloadImage(QNetworkRequest request) {\r
2113                 QFileDialog fd = new QFileDialog(this);\r
2114                 fd.setFileMode(FileMode.AnyFile);\r
2115                 fd.setConfirmOverwrite(true);\r
2116                 fd.setWindowTitle(tr("Save File"));\r
2117                 fd.setAcceptMode(AcceptMode.AcceptSave);\r
2118                 fd.setDirectory(System.getProperty("user.home"));\r
2119                 String name = request.url().toString();\r
2120                 name = name.replace("nnres://", "");\r
2121                 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());\r
2122                 name = name.replace(dPath, "");\r
2123                 int pos = name.lastIndexOf('.');\r
2124                 String guid = name;\r
2125                 if (pos > -1) {\r
2126                         String mimeType = "(*." + name.substring(pos + 1)\r
2127                         + ");; All Files (*)";\r
2128                                 fd.setFilter(tr(mimeType));\r
2129                         guid = guid.substring(0,pos);\r
2130                 }\r
2131                 pos = name.lastIndexOf(Global.attachmentNameDelimeter);\r
2132                 if (pos > -1) {\r
2133                         guid = name.substring(0, pos);\r
2134                         fd.selectFile(name.substring(pos+Global.attachmentNameDelimeter.length()));             \r
2135                 }\r
2136                 if (fd.exec() != 0 && fd.selectedFiles().size() > 0) {\r
2137                         Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);\r
2138                         String fileName = fd.selectedFiles().get(0);\r
2139                         QFile saveFile = new QFile(fileName);\r
2140                         QFile.OpenMode mode = new QFile.OpenMode();\r
2141                         mode.set(QFile.OpenModeFlag.WriteOnly);\r
2142                         saveFile.open(mode);\r
2143                         QDataStream saveOut = new QDataStream(saveFile);\r
2144                         QByteArray binData = new QByteArray(resBinary.getData().getBody());\r
2145                         saveOut.writeBytes(binData.toByteArray());\r
2146                         saveFile.close();\r
2147                 }\r
2148         }\r
2149 \r
2150         \r
2151         // *************************************************************\r
2152         // * decrypt any hidden text.  We could do an XML parse, but \r
2153         // * it is quicker here just to scan for an <img tag & do the fix\r
2154         // * the manual way\r
2155         // *************************************************************\r
2156         private void removeEncryption(String id, String plainText, boolean permanent, String slot) {\r
2157                 if (!permanent) {\r
2158                         plainText = " <en-crypt-temp slot=\""+slot  +"\">" +plainText+"</en-crypt-temp> ";\r
2159                 }\r
2160                 \r
2161                 String html = browser.page().mainFrame().toHtml();\r
2162                 String text = html;\r
2163                 int imagePos = html.indexOf("<img");\r
2164                 int endPos;\r
2165                 for ( ;imagePos>0; ) {\r
2166                         // Find the end tag\r
2167                         endPos = text.indexOf(">", imagePos);\r
2168                         String tag = text.substring(imagePos-1,endPos);\r
2169                         if (tag.indexOf("id=\""+id+"\"") > -1) {\r
2170                                         text = text.substring(0,imagePos) +plainText+text.substring(endPos+1);\r
2171                                                                                 \r
2172                                         browser.setContent(new QByteArray(text));\r
2173                                         contentChanged();\r
2174                         }\r
2175                         imagePos = text.indexOf("<img", imagePos+1);\r
2176                 }\r
2177         }\r
2178         \r
2179         \r
2180         //****************************************************************\r
2181         //* Focus shortcuts\r
2182         //****************************************************************\r
2183         @SuppressWarnings("unused")\r
2184         private void focusTitle() {\r
2185                 titleLabel.setFocus();\r
2186         }\r
2187         @SuppressWarnings("unused")\r
2188         private void focusTag() {\r
2189                 tagEdit.setFocus();\r
2190         }\r
2191         @SuppressWarnings("unused")\r
2192         private void focusNote() {\r
2193                 browser.setFocus();\r
2194         }\r
2195         @SuppressWarnings("unused")\r
2196         private void focusAuthor() {\r
2197                 authorLabel.setFocus();\r
2198         }\r
2199         @SuppressWarnings("unused")\r
2200         private void focusUrl() {\r
2201                 urlLabel.setFocus();\r
2202         }\r
2203         \r
2204 \r
2205         //*****************************************************************\r
2206         //* Set the document background color\r
2207         //*****************************************************************\r
2208         public void setBackgroundColor(String color) {\r
2209                 String js = "function changeBackground(color) {"\r
2210                         +"document.body.style.background = color;"\r
2211                         +"}" \r
2212                         +"changeBackground('" +color+"');";\r
2213                 browser.page().mainFrame().evaluateJavaScript(js);\r
2214                 contentChanged();\r
2215         }\r
2216         \r
2217         \r
2218         //****************************************************************\r
2219         //* MicroFocus changed\r
2220         //****************************************************************\r
2221         private void microFocusChanged() {\r
2222                 boldButton.setDown(false);\r
2223                 italicButton.setDown(false);\r
2224                 underlineButton.setDown(false);\r
2225                 browser.openAction.setEnabled(false);\r
2226                 browser.downloadAttachment.setEnabled(false);\r
2227                 browser.downloadImage.setEnabled(false);\r
2228                 browser.rotateImageLeft.setEnabled(false);\r
2229                 browser.rotateImageRight.setEnabled(false);\r
2230                 browser.insertTableAction.setEnabled(true);\r
2231                 browser.insertTableRowAction.setEnabled(false);\r
2232                 browser.deleteTableRowAction.setEnabled(false);\r
2233                 browser.insertLinkAction.setText(tr("Insert Hyperlink"));\r
2234                 currentHyperlink ="";\r
2235                 insideList = false;\r
2236                 forceTextPaste = false;\r
2237                 \r
2238                 String js = new String( "function getCursorPos() {"\r
2239                         +"var cursorPos;"\r
2240                         +"if (window.getSelection) {"\r
2241                         +"   var selObj = window.getSelection();"\r
2242                         +"   var selRange = selObj.getRangeAt(0);"\r
2243                         +"   var workingNode = window.getSelection().anchorNode.parentNode;"\r
2244                         +"   while(workingNode != null) { " \r
2245 //                      +"      window.jambi.printNode(workingNode.nodeName);"\r
2246                         +"      if (workingNode.nodeName=='EN-CRYPT-TEMP') window.jambi.forceTextPaste();"\r
2247                         +"      if (workingNode.nodeName=='B') window.jambi.boldActive();"\r
2248                         +"      if (workingNode.nodeName=='I') window.jambi.italicActive();"\r
2249                         +"      if (workingNode.nodeName=='U') window.jambi.underlineActive();"\r
2250                         +"      if (workingNode.nodeName=='UL') window.jambi.setInsideList();"\r
2251                         +"      if (workingNode.nodeName=='OL') window.jambi.setInsideList();"\r
2252                         +"      if (workingNode.nodeName=='LI') window.jambi.setInsideList();"\r
2253                         +"      if (workingNode.nodeName=='TBODY') window.jambi.setInsideTable();"\r
2254                         +"      if (workingNode.nodeName=='A') {for(var x = 0; x < workingNode.attributes.length; x++ ) {if (workingNode.attributes[x].nodeName.toLowerCase() == 'href') window.jambi.setInsideLink(workingNode.attributes[x].nodeValue);}}"\r
2255                         +"      if (workingNode.nodeName=='SPAN') {"\r
2256                         +"         if (workingNode.getAttribute('style') == 'text-decoration: underline;') window.jambi.underlineActive();"\r
2257                         +"      }"\r
2258                         +"      workingNode = workingNode.parentNode;"\r
2259                         +"   }"\r
2260                         +"}"\r
2261                         +"} getCursorPos();");\r
2262                 browser.page().mainFrame().evaluateJavaScript(js);\r
2263         }\r
2264         \r
2265         public void printNode(String n) {\r
2266                 System.out.println("Node Vaule: " +n);\r
2267         }\r
2268         \r
2269         \r
2270         //****************************************************************\r
2271         //* Insert a table row\r
2272         //****************************************************************\r
2273         public void insertTableRow() {\r
2274                 \r
2275                 String js = new String( "function insertTableRow() {"\r
2276                         +"   var selObj = window.getSelection();"\r
2277                         +"   var selRange = selObj.getRangeAt(0);"\r
2278                         +"   var workingNode = window.getSelection().anchorNode.parentNode;"\r
2279                         +"   var cellCount = 0;"\r
2280                         +"   while(workingNode != null) { " \r
2281                         +"      if (workingNode.nodeName.toLowerCase()=='tr') {"\r
2282                         +"           row = document.createElement('TR');"\r
2283                         +"           var nodes = workingNode.getElementsByTagName('td');"\r
2284                         +"           for (j=0; j<nodes.length; j=j+1) {"\r
2285                         +"              cell = document.createElement('TD');"\r
2286                         +"              cell.innerHTML='&nbsp;';"\r
2287                         +"              row.appendChild(cell);"\r
2288                         +"           }"                 \r
2289                         +"           workingNode.parentNode.insertBefore(row,workingNode.nextSibling);"\r
2290                         +"           return;"\r
2291                         +"      }"\r
2292                         +"      workingNode = workingNode.parentNode;"\r
2293                         +"   }"\r
2294                         +"} insertTableRow();");\r
2295                 browser.page().mainFrame().evaluateJavaScript(js);\r
2296                 contentChanged();\r
2297         }\r
2298         //****************************************************************\r
2299         //* Insert a table row\r
2300         //****************************************************************\r
2301         public void deleteTableRow() {\r
2302                 \r
2303                 String js = new String( "function deleteTableRow() {"\r
2304                         +"   var selObj = window.getSelection();"\r
2305                         +"   var selRange = selObj.getRangeAt(0);"\r
2306                         +"   var workingNode = window.getSelection().anchorNode.parentNode;"\r
2307                         +"   var cellCount = 0;"\r
2308                         +"   while(workingNode != null) { " \r
2309                         +"      if (workingNode.nodeName.toLowerCase()=='tr') {"\r
2310                         +"           workingNode.parentNode.removeChild(workingNode);"\r
2311                         +"           return;"\r
2312                         +"      }"\r
2313                         +"      workingNode = workingNode.parentNode;"\r
2314                         +"   }"\r
2315                         +"} deleteTableRow();");\r
2316                 browser.page().mainFrame().evaluateJavaScript(js);\r
2317                 contentChanged();\r
2318         }\r
2319         public void setInsideTable() {\r
2320                 browser.insertTableRowAction.setEnabled(true);\r
2321                 browser.deleteTableRowAction.setEnabled(true);\r
2322                 browser.insertTableAction.setEnabled(false);\r
2323                 browser.encryptAction.setEnabled(false);\r
2324         }\r
2325         \r
2326         public void setInsideLink(String link) {\r
2327                 browser.insertLinkAction.setText(tr("Edit Hyperlink"));\r
2328                 currentHyperlink = link;\r
2329         }\r
2330         \r
2331         public void italicActive() {\r
2332                 italicButton.setDown(true);\r
2333         }\r
2334         public void boldActive() {\r
2335                 boldButton.setDown(true);\r
2336         }\r
2337         public void underlineActive() {\r
2338                 underlineButton.setDown(true);\r
2339         }\r
2340         public void forceTextPaste() {\r
2341                 forceTextPaste = true;\r
2342         }\r
2343         public void imageContextMenu(String f) {\r
2344                 browser.downloadImage.setEnabled(true);\r
2345                 browser.rotateImageRight.setEnabled(true);\r
2346                 browser.rotateImageLeft.setEnabled(true);\r
2347                 browser.openAction.setEnabled(true);\r
2348                 selectedFile = f;\r
2349         }\r
2350         public void rotateImageRight() {\r
2351                 QWebSettings.setMaximumPagesInCache(0);\r
2352                 QWebSettings.setObjectCacheCapacities(0, 0, 0);\r
2353                 QImage image = new QImage(selectedFile);\r
2354                 QMatrix matrix = new QMatrix();\r
2355                 matrix.rotate( 90.0 );\r
2356                 image = image.transformed(matrix);\r
2357                 image.save(selectedFile);\r
2358                 QWebSettings.setMaximumPagesInCache(0);\r
2359                 QWebSettings.setObjectCacheCapacities(0, 0, 0);\r
2360                 browser.setHtml(browser.page().mainFrame().toHtml());\r
2361                 browser.reload();\r
2362                 contentChanged();\r
2363 //              resourceSignal.contentChanged.emit(selectedFile);\r
2364 \r
2365         }\r
2366         public void rotateImageLeft() {\r
2367                 QImage image = new QImage(selectedFile);\r
2368                 QMatrix matrix = new QMatrix();\r
2369                 matrix.rotate( -90.0 );\r
2370                 image = image.transformed(matrix);\r
2371                 image.save(selectedFile);\r
2372                 browser.setHtml(browser.page().mainFrame().toHtml());\r
2373                 browser.reload();\r
2374                 contentChanged();\r
2375 //              resourceSignal.contentChanged.emit(selectedFile);\r
2376         }\r
2377         public void resourceContextMenu(String f) {\r
2378                 browser.downloadAttachment.setEnabled(true);\r
2379                 browser.openAction.setEnabled(true);\r
2380                 selectedFile = f;\r
2381         }\r
2382         \r
2383         \r
2384         //****************************************************************\r
2385         //* Apply CSS style to specified word\r
2386         //****************************************************************\r
2387 /*      public void applyStyleToWords(String word, String style) {\r
2388                 QFile script = new QFile("D:\\NeverNote\\js\\hilight1.js");\r
2389                 script.open(OpenModeFlag.ReadOnly);\r
2390                 String s = script.readAll().toString();\r
2391                 String js = new String(s +" findit('"+word+"', '"+style+"');");\r
2392                 browser.page().mainFrame().evaluateJavaScript(js);\r
2393                 System.out.println(getContent());\r
2394         }\r
2395 */      \r
2396         //****************************************************************\r
2397         //* Someone tried to paste a resource between notes, so we need  *\r
2398         //* to do some special handling.                                 *\r
2399         //****************************************************************\r
2400         private String fixInternotePaste(String text) {\r
2401                 logger.log(logger.EXTREME, "Fixing internote paste");\r
2402                 String returnValue = fixInternotePasteSearch(text, "<img", "src=\"");\r
2403                 return fixInternotePasteSearch(returnValue, "<a", "href=\"nnres://");\r
2404         }\r
2405         private String fixInternotePasteSearch(String text, String type, String locTag) {\r
2406                 \r
2407                 // First, let's fix the images.\r
2408                 int startPos = text.indexOf(type);\r
2409                 int endPos;\r
2410                 for (; startPos>=0;) {\r
2411                         endPos = text.indexOf(">", startPos+1);\r
2412                         String segment = text.substring(startPos, endPos);\r
2413                         if (segment.indexOf("en-tag") > -1) {\r
2414                                 String newSegment = segment;\r
2415                                 \r
2416                                 int guidStartPos = segment.indexOf("guid=\"");\r
2417                                 int guidEndPos = segment.indexOf("\"", guidStartPos+7);\r
2418                                 String guid = segment.substring(guidStartPos+6,guidEndPos);\r
2419                                 \r
2420                                 int mimeStartPos = segment.indexOf("type");\r
2421                                 int mimeEndPos = segment.indexOf("\"", mimeStartPos+7);\r
2422                                 String mime = segment.substring(mimeStartPos+6,mimeEndPos);\r
2423 \r
2424                                 int srcStartPos = segment.indexOf("src");\r
2425                                 int srcEndPos = segment.indexOf("\"", srcStartPos+6);\r
2426                                 String src = segment.substring(srcStartPos+5,srcEndPos);\r
2427                                 \r
2428                                 Calendar currentTime = new GregorianCalendar();\r
2429                                 Long l = new Long(currentTime.getTimeInMillis());\r
2430                                 long prevTime = l;\r
2431                                 while (l==prevTime) {\r
2432                                         currentTime = new GregorianCalendar();\r
2433                                         l= new Long(currentTime.getTimeInMillis());\r
2434                                 }\r
2435                                 \r
2436                                 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);\r
2437                                 // if r==null, then the image doesn't exist (it was probably cut out of another note, so \r
2438                                 // we need to recereate it\r
2439                                 if (r==null) {\r
2440                                         r = createResource(src, 1, mime, false);\r
2441                                         if (r==null)\r
2442                                                 return "";\r
2443                                 }\r
2444                         String randint = new String(Long.toString(l));\r
2445                         String extension = null;\r
2446                         if (r.getMime()!= null) {\r
2447                                 extension = r.getMime().toLowerCase();\r
2448                                 if (extension.indexOf("/")>-1)\r
2449                                         extension = extension.substring(extension.indexOf("/")+1);\r
2450                         }\r
2451                         String newFile = randint;\r
2452                         if (r.getAttributes().getFileName() != null && r.getAttributes().getFileName() != "")\r
2453                                 if (!locTag.startsWith("src"))\r
2454                                         newFile = newFile+Global.attachmentNameDelimeter+r.getAttributes().getFileName();\r
2455                         r.setNoteGuid(currentNote.getGuid());\r
2456                         \r
2457                         r.setGuid(randint);\r
2458                         conn.getNoteTable().noteResourceTable.saveNoteResource(r, true);\r
2459                                 QFile f = new QFile(Global.getFileManager().getResDirPath(newFile));\r
2460                                 QByteArray bin = new QByteArray(r.getData().getBody());\r
2461                                 f.open(QFile.OpenModeFlag.WriteOnly);\r
2462                                 f.write(bin);\r
2463                                 f.close();\r
2464                                 newSegment = newSegment.replace("guid=\""+guid, "guid=\""+randint);\r
2465                                 currentNote.getResources().add(r);\r
2466                                 \r
2467                                 int startSrcPos = newSegment.indexOf(locTag);\r
2468                                 int endSrcPos = newSegment.indexOf("\"",startSrcPos+locTag.length()+1);\r
2469                                 String source; \r
2470                                 if (locTag.startsWith("src")) {\r
2471                                          source = newSegment.substring(startSrcPos+locTag.length(),endSrcPos);\r
2472                                                 newSegment = newSegment.replace(source,\r
2473                                                         FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath(newFile)));\r
2474                                 } else {\r
2475                                         source = newSegment.substring(startSrcPos+locTag.length(),endSrcPos);\r
2476                                         newSegment = newSegment.replace(source, newFile);\r
2477                                 }\r
2478                                 \r
2479                                 text = text.substring(0,startPos) + newSegment + text.substring(endPos);\r
2480                         }\r
2481                         startPos = text.indexOf(type, startPos+1);\r
2482                 }\r
2483                 return text;\r
2484         }\r
2485 \r
2486 \r
2487         public void nextPage(String file) {\r
2488                 logger.log(logger.EXTREME, "Starting nextPage()");\r
2489                 \r
2490                 Integer pageNumber;\r
2491                 if (previewPageList.containsKey(file))\r
2492                         pageNumber = previewPageList.get(file)+1;\r
2493                 else\r
2494                         pageNumber = 2;\r
2495                 previewPageList.remove(file);\r
2496                 previewPageList.put(file, pageNumber);\r
2497                 PDFPreview pdfPreview = new PDFPreview();\r
2498                 boolean goodPreview = pdfPreview.setupPreview(file, "pdf", pageNumber);\r
2499                 if (goodPreview) {\r
2500 \r
2501 //                      String html = getContent();\r
2502                         QWebSettings.setMaximumPagesInCache(0);\r
2503                         QWebSettings.setObjectCacheCapacities(0, 0, 0);\r
2504 //                      browser.setContent(new QByteArray());\r
2505                         browser.setHtml(browser.page().mainFrame().toHtml());\r
2506                         browser.reload();\r
2507 //                      browser.setContent(new QByteArray(html));\r
2508 //                      browser.triggerPageAction(WebAction.Reload);\r
2509 //                      pdfMouseOver(selectedFile);\r
2510                 }\r
2511         }\r
2512 \r
2513         public void previousPage(String file) {\r
2514                 logger.log(logger.EXTREME, "Starting previousPage()");\r
2515                 \r
2516                 Integer pageNumber;\r
2517                 if (previewPageList.containsKey(file))\r
2518                         pageNumber = previewPageList.get(file)-1;\r
2519                 else\r
2520                         pageNumber = 1;\r
2521                 previewPageList.remove(file);\r
2522                 previewPageList.put(file, pageNumber);\r
2523                 PDFPreview pdfPreview = new PDFPreview();\r
2524                 boolean goodPreview = pdfPreview.setupPreview(file, "pdf", pageNumber);\r
2525                 if (goodPreview) {\r
2526 \r
2527 //                      String html = getContent();\r
2528                         QWebSettings.setMaximumPagesInCache(0);\r
2529                         QWebSettings.setObjectCacheCapacities(0, 0, 0);\r
2530                         browser.setHtml(browser.page().mainFrame().toHtml());\r
2531                         browser.reload();\r
2532 //                      browser.setContent(new QByteArray(html));\r
2533 //                      browser.triggerPageAction(WebAction.Reload);\r
2534                 }\r
2535         }\r
2536         \r
2537 /*      public void pdfMouseOver(String name) { \r
2538                 int pageNumber;\r
2539                 if (previewPageList.containsKey(selectedFile))\r
2540                         pageNumber = previewPageList.get(selectedFile)+1;\r
2541                 else\r
2542                         pageNumber = 1;\r
2543                 \r
2544                 if (pageNumber <= 1)\r
2545                         browser.previousPageAction.setEnabled(false);\r
2546                 else\r
2547                         browser.previousPageAction.setEnabled(true);\r
2548                 \r
2549                 PDFPreview pdf = new PDFPreview();\r
2550                 int totalPages = pdf.getPageCount(name);\r
2551                 if (previewPageList.containsKey(selectedFile))\r
2552                         pageNumber = previewPageList.get(selectedFile)+1;\r
2553                 else\r
2554                         pageNumber = 1;\r
2555                 if (totalPages > pageNumber)\r
2556                         browser.nextPageAction.setEnabled(true);\r
2557                 else\r
2558                         browser.nextPageAction.setEnabled(false);\r
2559         }\r
2560         \r
2561 \r
2562         public void pdfMouseOut() { \r
2563 //              browser.nextPageAction.setVisible(false);\r
2564 //              browser.previousPageAction.setVisible(false);\r
2565         }\r
2566 */\r
2567         \r
2568         private void toggleUndoVisible(Boolean toggle) {\r
2569                 undoAction.setVisible(toggle);\r
2570                 Global.saveEditorButtonsVisible("undo", toggle);\r
2571         }\r
2572         private void toggleRedoVisible(Boolean toggle) {\r
2573                 redoAction.setVisible(toggle);\r
2574                 Global.saveEditorButtonsVisible("redo", toggle);\r
2575         }\r
2576         private void toggleCutVisible(Boolean toggle) {\r
2577                 cutAction.setVisible(toggle);\r
2578                 Global.saveEditorButtonsVisible("cut", toggle);\r
2579         }\r
2580         private void toggleCopyVisible(Boolean toggle) {\r
2581                 copyAction.setVisible(toggle);\r
2582                 Global.saveEditorButtonsVisible("copy", toggle);\r
2583         }\r
2584         private void togglePasteVisible(Boolean toggle) {\r
2585                 pasteAction.setVisible(toggle);\r
2586                 Global.saveEditorButtonsVisible("paste", toggle);\r
2587         }\r
2588         private void toggleBoldVisible(Boolean toggle) {\r
2589                 boldAction.setVisible(toggle);\r
2590                 Global.saveEditorButtonsVisible("bold", toggle);\r
2591         }\r
2592         private void toggleItalicVisible(Boolean toggle) {\r
2593                 italicAction.setVisible(toggle);\r
2594                 Global.saveEditorButtonsVisible("italic", toggle);\r
2595         }\r
2596         private void toggleUnderlineVisible(Boolean toggle) {\r
2597                 underlineAction.setVisible(toggle);\r
2598                 Global.saveEditorButtonsVisible("underline", toggle);\r
2599         }\r
2600         private void toggleStrikethroughVisible(Boolean toggle) {\r
2601                 strikethroughAction.setVisible(toggle);\r
2602                 Global.saveEditorButtonsVisible("strikethrough", toggle);\r
2603         }\r
2604         private void toggleLeftAlignVisible(Boolean toggle) {\r
2605                 leftAlignAction.setVisible(toggle);\r
2606                 Global.saveEditorButtonsVisible("alignLeft", toggle);\r
2607         }\r
2608         private void toggleRightAlignVisible(Boolean toggle) {\r
2609                 rightAlignAction.setVisible(toggle);\r
2610                 Global.saveEditorButtonsVisible("alignRight", toggle);\r
2611         }       \r
2612         private void toggleCenterAlignVisible(Boolean toggle) {\r
2613                 centerAlignAction.setVisible(toggle);\r
2614                 Global.saveEditorButtonsVisible("alignCenter", toggle);\r
2615         }\r
2616         private void toggleHLineVisible(Boolean toggle) {\r
2617                 hlineAction.setVisible(toggle);\r
2618                 Global.saveEditorButtonsVisible("hline", toggle);\r
2619         }\r
2620         private void toggleIndentVisible(Boolean toggle) {\r
2621                 indentAction.setVisible(toggle);\r
2622                 Global.saveEditorButtonsVisible("indent", toggle);\r
2623         }\r
2624         private void toggleOutdentVisible(Boolean toggle) {\r
2625                 outdentAction.setVisible(toggle);\r
2626                 Global.saveEditorButtonsVisible("outdent", toggle);\r
2627         }\r
2628         private void toggleBulletListVisible(Boolean toggle) {\r
2629                 bulletListAction.setVisible(toggle);\r
2630                 Global.saveEditorButtonsVisible("bulletList", toggle);\r
2631         }\r
2632         private void toggleNumberListVisible(Boolean toggle) {\r
2633                 numberListAction.setVisible(toggle);\r
2634                 Global.saveEditorButtonsVisible("numberList", toggle);\r
2635         }\r
2636         private void toggleFontListVisible(Boolean toggle) {\r
2637                 fontListAction.setVisible(toggle);\r
2638                 Global.saveEditorButtonsVisible("font", toggle);\r
2639         }\r
2640         private void toggleFontColorVisible(Boolean toggle) {\r
2641                 fontColorAction.setVisible(toggle);\r
2642                 Global.saveEditorButtonsVisible("fontColor", toggle);\r
2643         }\r
2644         private void toggleFontSizeVisible(Boolean toggle) {\r
2645                 fontSizeAction.setVisible(toggle);\r
2646                 Global.saveEditorButtonsVisible("fontSize", toggle);\r
2647         }\r
2648         private void toggleFontHilightVisible(Boolean toggle) {\r
2649                 fontHilightAction.setVisible(toggle);\r
2650                 Global.saveEditorButtonsVisible("fontHilight", toggle);\r
2651         }\r
2652         private void toggleSpellCheckVisible(Boolean toggle) {\r
2653                 spellCheckAction.setVisible(toggle);\r
2654                 Global.saveEditorButtonsVisible("spellCheck", toggle);\r
2655         }\r
2656 \r
2657 \r
2658         private void setupDictionary() {\r
2659                 File wordList = new File(Global.getFileManager().getSpellDirPath()+Locale.getDefault()+".dic");\r
2660                 try {\r
2661                         dictionary = new SpellDictionaryHashMap(wordList);\r
2662                         spellChecker = new SpellChecker(dictionary);\r
2663                         File userWordList;\r
2664                         userWordList = new File(Global.getFileManager().getSpellDirPathUser()+"user.dic");\r
2665                         \r
2666                         // Get the local user spell dictionary\r
2667                         try {\r
2668                                 userDictionary = new SpellDictionaryHashMap(userWordList);\r
2669                         } catch (FileNotFoundException e) {\r
2670                                 userWordList.createNewFile();\r
2671                                 userDictionary = new SpellDictionaryHashMap(userWordList);\r
2672                         } catch (IOException e) {\r
2673                                 userWordList.createNewFile();\r
2674                                 userDictionary = new SpellDictionaryHashMap(userWordList);\r
2675                         }\r
2676                         \r
2677                         spellListener = new SuggestionListener(this, spellChecker);\r
2678                         \r
2679                         // Add the user dictionary\r
2680                         spellChecker.addSpellCheckListener(spellListener);\r
2681                         spellChecker.setUserDictionary(userDictionary);\r
2682 \r
2683                 } catch (FileNotFoundException e) {\r
2684                         QMessageBox.critical(this, tr("Spell Check Error"), \r
2685                                         tr("Dictionary "+ Global.getFileManager().getSpellDirPath()+Locale.getDefault()+\r
2686                                                 ".dic was not found."));\r
2687                 } catch (IOException e) {\r
2688                         QMessageBox.critical(this, tr("Spell Check Error"), \r
2689                                         tr("Dictionary "+ Global.getFileManager().getSpellDirPath()+Locale.getDefault()+\r
2690                                                 ".dic is invalid."));\r
2691                 }\r
2692 \r
2693         }\r
2694         \r
2695         // Invoke spell checker dialog\r
2696         private void spellCheckClicked() {\r
2697 \r
2698                 if (spellChecker == null) {\r
2699                         setupDictionary();      \r
2700                 }\r
2701 \r
2702                 spellListener.abortSpellCheck = false;\r
2703                 String content = getBrowser().page().mainFrame().toPlainText();\r
2704                 StringWordTokenizer tokenizer = new StringWordTokenizer(content);\r
2705                 if (!tokenizer.hasMoreWords())\r
2706                         return;\r
2707                 getBrowser().page().action(WebAction.MoveToStartOfDocument);\r
2708 \r
2709                 getBrowser().setFocus();\r
2710                 boolean found;\r
2711                         \r
2712                 // Move to the start of page\r
2713                 KeyboardModifiers ctrl = new KeyboardModifiers(KeyboardModifier.ControlModifier.value());\r
2714                 QKeyEvent home = new QKeyEvent(Type.KeyPress, Key.Key_Home.value(), ctrl);  \r
2715                 browser.keyPressEvent(home);\r
2716                 getBrowser().setFocus();\r
2717                         \r
2718                 tokenizer = new StringWordTokenizer(content);\r
2719                 String word;\r
2720                         \r
2721                 while(tokenizer.hasMoreWords()) {\r
2722                         word = tokenizer.nextWord();\r
2723                         found = getBrowser().page().findText(word);\r
2724                         if (found && !spellListener.abortSpellCheck) {\r
2725                                 spellChecker.checkSpelling(new StringWordTokenizer(word));\r
2726                                 getBrowser().setFocus();\r
2727                         }\r
2728                 }\r
2729 \r
2730                 // Go to the end of the document & finish up.\r
2731                 home = new QKeyEvent(Type.KeyPress, Key.Key_End.value(), ctrl);  \r
2732                 browser.keyPressEvent(home);\r
2733                 if (!spellListener.errorsFound)\r
2734                         QMessageBox.information(this, tr("Spell Check Complete"), \r
2735                                         tr("No spelling errors found"));\r
2736 \r
2737     }\r
2738 \r
2739 }\r