OSDN Git Service

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