OSDN Git Service

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