OSDN Git Service

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