OSDN Git Service

17674e140395ce9ea4881d9c042f7757aab89139
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / xml / NoteFormatter.java
1 package cx.fbn.nevernote.xml;\r
2 \r
3 import java.io.ByteArrayInputStream;\r
4 import java.io.ByteArrayOutputStream;\r
5 import java.io.File;\r
6 import java.util.ArrayList;\r
7 import java.util.List;\r
8 \r
9 import org.w3c.tidy.Tidy;\r
10 import org.w3c.tidy.TidyMessage;\r
11 \r
12 import com.evernote.edam.type.Note;\r
13 import com.evernote.edam.type.Resource;\r
14 import com.trolltech.qt.core.QByteArray;\r
15 import com.trolltech.qt.core.QDataStream;\r
16 import com.trolltech.qt.core.QFile;\r
17 import com.trolltech.qt.core.QIODevice;\r
18 import com.trolltech.qt.core.QIODevice.OpenModeFlag;\r
19 import com.trolltech.qt.core.QTemporaryFile;\r
20 import com.trolltech.qt.core.QTextCodec;\r
21 import com.trolltech.qt.core.QUrl;\r
22 import com.trolltech.qt.core.Qt.BGMode;\r
23 import com.trolltech.qt.gui.QColor;\r
24 import com.trolltech.qt.gui.QPainter;\r
25 import com.trolltech.qt.gui.QPainter.RenderHint;\r
26 import com.trolltech.qt.gui.QPixmap;\r
27 import com.trolltech.qt.xml.QDomAttr;\r
28 import com.trolltech.qt.xml.QDomDocument;\r
29 import com.trolltech.qt.xml.QDomElement;\r
30 import com.trolltech.qt.xml.QDomNodeList;\r
31 \r
32 import cx.fbn.nevernote.Global;\r
33 import cx.fbn.nevernote.config.FileManager;\r
34 import cx.fbn.nevernote.filters.EnSearch;\r
35 import cx.fbn.nevernote.gui.PDFPreview;\r
36 import cx.fbn.nevernote.sql.DatabaseConnection;\r
37 import cx.fbn.nevernote.utilities.ApplicationLogger;\r
38 \r
39 public class NoteFormatter {\r
40 \r
41         private final ApplicationLogger logger;\r
42         private final DatabaseConnection conn;\r
43         public boolean resourceError = false;\r
44         public boolean readOnly = false; \r
45         public boolean inkNote = false;\r
46         public boolean addHighlight = true;\r
47         private Note currentNote;\r
48         private String currentNoteGuid;\r
49         private boolean pdfPreview;\r
50         ArrayList<QTemporaryFile> tempFiles;\r
51         private EnSearch enSearch;\r
52         private boolean noteHistory;\r
53         public boolean formatError;\r
54         \r
55         public NoteFormatter(ApplicationLogger logger, DatabaseConnection conn, List<QTemporaryFile> tempFiles2) {\r
56                 this.logger = logger;\r
57                 this.conn = conn;\r
58                 noteHistory = false;\r
59         }\r
60         \r
61         \r
62         private class TidyListener implements org.w3c.tidy.TidyMessageListener {\r
63                 \r
64                 ApplicationLogger logger;\r
65                 public boolean errorFound; \r
66                 \r
67                 public TidyListener(ApplicationLogger logger) {\r
68                         this.logger = logger;\r
69                         errorFound = false;\r
70                 }\r
71                 @Override\r
72                 public void messageReceived(TidyMessage msg) {\r
73                         if (msg.getLevel() == TidyMessage.Level.ERROR) {\r
74                                 logger.log(logger.LOW, "******* JTIDY ERORR *******");\r
75                                 logger.log(logger.LOW, "Error Code: " +msg.getErrorCode());\r
76                                 logger.log(logger.LOW, "Column: " +msg.getColumn());\r
77                                 logger.log(logger.LOW, "Column: " +msg.getColumn());\r
78                                 logger.log(logger.LOW, "Line: " +msg.getLine());\r
79                                 logger.log(logger.LOW, "Message: " +msg.getMessage());\r
80                                 logger.log(logger.LOW, "***************************");\r
81                                 errorFound = true;\r
82                         } else \r
83                                 logger.log(logger.EXTREME, "JTidy Results: "+msg.getMessage());\r
84                 }\r
85                 \r
86         }\r
87 \r
88         \r
89         \r
90         public void setNote(Note note, boolean pdfPreview) {\r
91                 currentNote = note;\r
92                 this.pdfPreview = pdfPreview;\r
93                 readOnly = false;\r
94                 currentNoteGuid = null;\r
95                 if (note != null) {\r
96                         currentNoteGuid = note.getGuid();\r
97                         readOnly = conn.getNotebookTable().isReadOnly(note.getNotebookGuid());\r
98                 } \r
99                 resourceError = false;\r
100         }\r
101         \r
102         public void setHighlight(EnSearch search) {\r
103                 if (search==null || search.hilightWords == null ||search.hilightWords.size() == 0) {\r
104                         enSearch = null;\r
105                         addHighlight = false;\r
106                 } else {\r
107                         enSearch = search;\r
108                         addHighlight = true;\r
109                 }\r
110         }\r
111         \r
112         // Set if we are coming here through note histary.  It triggers longer file names to avoid conflicts\r
113         public void setNoteHistory(boolean value) {\r
114                 noteHistory = value;\r
115         }\r
116         \r
117         // Rebuild the note HTML to something usable\r
118         public String rebuildNoteHTML() {\r
119                 formatError = false;\r
120                 if (currentNote == null)\r
121                         return null;\r
122                 logger.log(logger.HIGH, "Entering NeverNote.rebuildNoteHTML");\r
123                 logger.log(logger.EXTREME, "Note guid: " +currentNoteGuid);\r
124                 logger.log(logger.EXTREME, "Note Text:" +currentNote);\r
125                 QDomDocument doc = new QDomDocument();\r
126                 QDomDocument.Result result = doc.setContent(currentNote.getContent());\r
127 \r
128                 // Handle any errors\r
129                 if (!result.success) {\r
130                         logger.log(logger.LOW, "Error parsing document.  Attempting to restructure");\r
131                         Tidy tidy = new Tidy();\r
132                         TidyListener tidyListener = new TidyListener(logger);\r
133                         tidy.setMessageListener(tidyListener);\r
134                         tidy.getStderr().close();  // the listener will capture messages\r
135                         tidy.setXmlTags(true);\r
136                         \r
137                         QTextCodec codec;\r
138                         codec = QTextCodec.codecForName("UTF-8");\r
139                 QByteArray unicode =  codec.fromUnicode(currentNote.getContent());\r
140                 \r
141                 logger.log(logger.MEDIUM, "Starting JTidy check");\r
142                 logger.log(logger.MEDIUM, "Start of JTidy Input");\r
143                 logger.log(logger.MEDIUM, currentNote.getContent());\r
144                 logger.log(logger.MEDIUM, "End Of JTidy Input");\r
145                         ByteArrayInputStream is = new ByteArrayInputStream(unicode.toByteArray());\r
146                 ByteArrayOutputStream os = new ByteArrayOutputStream();\r
147                 tidy.setInputEncoding("UTF-8");\r
148                         tidy.parse(is, os);\r
149                         String tidyContent = os.toString();\r
150                         if (tidyListener.errorFound) {\r
151                                 logger.log(logger.LOW, "Restructure failed!!!");\r
152                         } else {\r
153                                 doc = null;\r
154                                 doc = new QDomDocument();\r
155                                 result = doc.setContent(tidyContent);\r
156                         }\r
157                 }\r
158                 if (!result.success) {\r
159                         logger.log(logger.MEDIUM, "Parse error when rebuilding XML to HTML");\r
160                         logger.log(logger.MEDIUM, "Note guid: " +currentNoteGuid);\r
161                         logger.log(logger.MEDIUM, "Error: "+result.errorMessage);\r
162                         logger.log(logger.MEDIUM, "Line: " +result.errorLine + " Column: " +result.errorColumn);\r
163                         System.out.println("Error: "+result.errorMessage);\r
164                         System.out.println("Line: " +result.errorLine + " Column: " +result.errorColumn);\r
165                         logger.log(logger.EXTREME, "**** Start of unmodified note HTML");\r
166                         logger.log(logger.EXTREME, currentNote.getContent());\r
167                         logger.log(logger.EXTREME, "**** End of unmodified note HTML");\r
168                         formatError = true;\r
169                         readOnly = true;\r
170                         return currentNote.getContent();\r
171                 }\r
172 \r
173                 if (tempFiles == null)\r
174                         tempFiles = new ArrayList<QTemporaryFile>();\r
175                 tempFiles.clear();\r
176                 \r
177                 doc = modifyTags(doc);\r
178                 if (addHighlight)\r
179                         doc = addHilight(doc);\r
180                 QDomElement docElem = doc.documentElement();\r
181                 docElem.setTagName("Body");\r
182 //              docElem.setAttribute("bgcolor", "green");\r
183                 logger.log(logger.EXTREME, "Rebuilt HTML:");\r
184                 logger.log(logger.EXTREME, doc.toString());     \r
185                 logger.log(logger.HIGH, "Leaving NeverNote.rebuildNoteHTML");\r
186                 // Fix the stupid problem where inserting an <img> tag after an <a> tag (which is done\r
187                 // to get the <en-media> application tag to work properly) causes spaces to be inserted\r
188                 // between the <a> & <img>.  This messes things up later.  This is an ugly hack.\r
189                 StringBuffer html = new StringBuffer(doc.toString());\r
190                 for (int i=html.indexOf("<a en-tag=\"en-media\" ", 0); i>-1; i=html.indexOf("<a en-tag=\"en-media\" ", i)) {\r
191                         i=html.indexOf(">\n",i+1);\r
192                         int z = html.indexOf("<img",i);\r
193                         for (int j=z-1; j>i; j--) \r
194                                 html.deleteCharAt(j);\r
195                         i=html.indexOf("/>", z+1);\r
196                         z = html.indexOf("</a>",i);\r
197                         for (int j=z-1; j>i+1; j--) \r
198                                 html.deleteCharAt(j);\r
199                 } \r
200 \r
201                 return html.toString(); //.replace("<Body", "<Body dir=\"rtl\"");\r
202         }       \r
203 \r
204         private void addImageHilight(String resGuid, QFile f) {\r
205                 if (enSearch == null || enSearch.hilightWords == null || enSearch.hilightWords.size() == 0)\r
206                         return;\r
207                 \r
208                 // Get the recognition XML that tells where to hilight on the image\r
209                 Resource recoResource = conn.getNoteTable().noteResourceTable.getNoteResourceRecognition(resGuid);\r
210                 if (recoResource.getRecognition().getBody() == null || recoResource.getRecognition().getBody().length == 0)\r
211                         return;\r
212                 QByteArray recoData = new QByteArray(recoResource.getRecognition().getBody());\r
213                 String xml = recoData.toString();\r
214                 \r
215                 // Get a painter for the image.  This is the background (the initial image).\r
216         QPixmap pix = new QPixmap(f.fileName());\r
217         QPixmap hilightedPix = new QPixmap(pix.size());\r
218         QPainter p = new QPainter(hilightedPix);\r
219         p.drawPixmap(0,0, pix);\r
220 \r
221         // Create a transparent pixmap.  The only non-transparent\r
222         // piece is the hilight that will be overlayed to hilight text no the background\r
223         QPixmap overlayPix = new QPixmap(pix.size());\r
224         overlayPix.fill(QColor.transparent);\r
225         QPainter p2 = new QPainter(overlayPix);\r
226         p2.setBackgroundMode(BGMode.TransparentMode);\r
227         p2.setRenderHint(RenderHint.Antialiasing, true);\r
228                 QColor yellow = QColor.yellow;\r
229 //              yellow.setAlphaF(0.4);\r
230         p2.setBrush(yellow);\r
231         \r
232                 // Get the recognition data from the note\r
233         QDomDocument doc = new QDomDocument();\r
234         doc.setContent(xml);\r
235         \r
236         // Go through all "item" nodes\r
237                 QDomNodeList anchors = doc.elementsByTagName("item");\r
238                 for (int i=0; i<anchors.length(); i++) {\r
239                         QDomElement element = anchors.at(i).toElement();\r
240                         int x = new Integer(element.attribute("x"));   // x coordinate\r
241                         int y = new Integer(element.attribute("y"));   // y coordinate\r
242                         int w = new Integer(element.attribute("w"));   // width\r
243                         int h = new Integer(element.attribute("h"));   // height\r
244                         QDomNodeList children = element.childNodes();  // all children ("t" nodes).\r
245                         \r
246                         // Go through the children ("t" nodes)\r
247                         for (int j=0; j<children.length(); j++) {\r
248                         QDomElement child = children.at(j).toElement();\r
249                         if (child.nodeName().equalsIgnoreCase("t")) {\r
250                                 String text = child.text();   // recognition text\r
251                                 int weight = new Integer(child.attribute("w"));  // recognition weight\r
252                                 if (weight >= Global.getRecognitionWeight()) {   // Are we above the maximum?\r
253                                         \r
254                                         // Check to see if this word matches something we were searching for.\r
255                                         for (int k=0; k<enSearch.hilightWords.size(); k++) {\r
256                                                 String searchWord = enSearch.hilightWords.get(k).toLowerCase();\r
257                                                 if (searchWord.startsWith("*"))\r
258                                                         searchWord = searchWord.substring(1);\r
259                                                 if (searchWord.endsWith("*"))\r
260                                                         searchWord = searchWord.substring(0,searchWord.length()-1);\r
261                                                 if (text.toLowerCase().contains(searchWord)) {\r
262                                                         p2.drawRect(x,y,w,h);                   \r
263                                                 }\r
264                                         }\r
265                                 }\r
266                         }\r
267                         }\r
268                 }\r
269         p2.end();\r
270         \r
271         // Paint the hilight onto the background.\r
272         p.setOpacity(0.4);\r
273         p.drawPixmap(0,0, overlayPix);\r
274         p.end();\r
275         \r
276         // Save over the initial pixmap.\r
277         hilightedPix.save(f.fileName());\r
278         }\r
279         \r
280     // Modify the en-media tag into an image tag so it can be displayed.\r
281     private void modifyImageTags(QDomDocument doc, QDomElement docElem, QDomElement enmedia, QDomAttr hash) {\r
282         logger.log(logger.HIGH, "Entering NeverNote.modifyImageTags");\r
283         String type = enmedia.attribute("type");\r
284         if (type.startsWith("image/"))\r
285                 type = "."+type.substring(6);\r
286         else\r
287                 type="";\r
288         \r
289         String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNoteGuid, hash.value());\r
290         QFile tfile = new QFile(Global.getFileManager().getResDirPath(resGuid + type));\r
291 //      if (!tfile.exists()) {\r
292                 Resource r = null;\r
293                 if (resGuid != null)\r
294                                 r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid,true);\r
295                         if (r==null || r.getData() == null || r.getData().getBody().length == 0) {\r
296                                 resourceError = true;\r
297                                 readOnly = true;\r
298                         }\r
299                         if (r!= null && r.getData() != null && r.getData().getBody().length > 0) {\r
300                                 tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly));\r
301                                 QByteArray binData = new QByteArray(r.getData().getBody());\r
302                                 tfile.write(binData);\r
303                                 tfile.close();\r
304                                 \r
305                                 // If we have recognition text, outline it\r
306                                 addImageHilight(r.getGuid(), tfile);\r
307                                 \r
308                                 enmedia.setAttribute("src", QUrl.fromLocalFile(tfile.fileName()).toString());\r
309                                 enmedia.setAttribute("en-tag", "en-media");\r
310                                 enmedia.setNodeValue("");\r
311                         enmedia.setAttribute("guid", r.getGuid());\r
312                         enmedia.setTagName("img");\r
313                 }\r
314 //      }\r
315         // Technically, we should do a file:// to have a proper url, but for some reason QWebPage hates\r
316         // them and won't generate a thumbnail image properly if we use them.\r
317 //              enmedia.setAttribute("src", QUrl.fromLocalFile(tfile.fileName()).toString());\r
318                 enmedia.setAttribute("src", tfile.fileName().toString());\r
319                 enmedia.setAttribute("en-tag", "en-media");\r
320                 enmedia.setTagName("img");\r
321                 if (r != null && r.getAttributes() != null && \r
322                                 (r.getAttributes().getSourceURL() == null || !r.getAttributes().getSourceURL().toLowerCase().startsWith("http://latex.codecogs.com/gif.latex?")))\r
323                         enmedia.setAttribute("onContextMenu", "window.jambi.imageContextMenu('" +tfile.fileName()  +"');");\r
324                 else {\r
325                         QDomElement newText = doc.createElement("a");\r
326                         enmedia.setAttribute("src", tfile.fileName().toString());\r
327                         enmedia.setAttribute("en-tag", "en-latex");\r
328                         newText.setAttribute("onMouseOver", "style.cursor='hand'");\r
329                         if (r!= null && r.getAttributes() != null && r.getAttributes().getSourceURL() != null)\r
330                                 newText.setAttribute("title", r.getAttributes().getSourceURL());\r
331                         newText.setAttribute("href", "latex://"+tfile.fileName().toString());\r
332                         enmedia.parentNode().replaceChild(newText, enmedia);\r
333                         newText.appendChild(enmedia);\r
334 \r
335                 }\r
336                 enmedia.setNodeValue("");\r
337                 enmedia.setAttribute("guid", resGuid);\r
338 \r
339 \r
340                 logger.log(logger.HIGH, "Leaving NeverNote.modifyImageTags");\r
341     }\r
342     \r
343     \r
344         // Modify tags from Evernote specific things to XHTML tags.\r
345         private QDomDocument modifyTags(QDomDocument doc) {\r
346                 logger.log(logger.HIGH, "Entering NeverNote.modifyTags");\r
347                 if (tempFiles == null)\r
348                         tempFiles = new ArrayList<QTemporaryFile>();\r
349                 tempFiles.clear();\r
350                 QDomElement docElem = doc.documentElement();\r
351                 \r
352                 // Modify en-media tags\r
353                 QDomNodeList anchors = docElem.elementsByTagName("en-media");\r
354                 int enMediaCount = anchors.length();\r
355                 for (int i=enMediaCount-1; i>=0; --i) {\r
356                         QDomElement enmedia = anchors.at(i).toElement();\r
357                         if (enmedia.hasAttribute("type")) {\r
358                                 QDomAttr attr = enmedia.attributeNode("type");\r
359                                 QDomAttr hash = enmedia.attributeNode("hash");\r
360                                 String[] type = attr.nodeValue().split("/");\r
361                                 String appl = type[1];\r
362                                 \r
363                                 if (type[0] != null) {\r
364                                         if (type[0].equals("image")) {\r
365                                                 modifyImageTags(doc, docElem, enmedia, hash);\r
366                                         }\r
367                                         if (!type[0].equals("image")) {\r
368                                                 modifyApplicationTags(doc, docElem, enmedia, hash, appl);\r
369                                         }\r
370                                 }\r
371                         }\r
372                 }\r
373                 \r
374                 // Modify todo tags\r
375                 anchors = docElem.elementsByTagName("en-todo");\r
376                 int enTodoCount = anchors.length();\r
377                 for (int i=enTodoCount-1; i>=0; i--) {\r
378                         QDomElement enmedia = anchors.at(i).toElement();\r
379                         modifyTodoTags(enmedia);\r
380                 }\r
381                 \r
382                 // Modify en-crypt tags\r
383                 anchors = docElem.elementsByTagName("en-crypt");\r
384                 int enCryptLen = anchors.length();\r
385                 for (int i=enCryptLen-1; i>=0; i--) {\r
386                         QDomElement enmedia = anchors.at(i).toElement();\r
387                         enmedia.setAttribute("contentEditable","false");\r
388                         enmedia.setAttribute("src", Global.getFileManager().getImageDirPath("encrypt.png"));\r
389                         enmedia.setAttribute("en-tag","en-crypt");\r
390                         enmedia.setAttribute("alt", enmedia.text());\r
391                         Global.cryptCounter++;\r
392                         enmedia.setAttribute("id", "crypt"+Global.cryptCounter.toString());\r
393                         String encryptedText = enmedia.text();\r
394                         \r
395                         // If the encryption string contains crlf at the end, remove them because they mess up the javascript.\r
396                         if (encryptedText.endsWith("\n"))\r
397                                 encryptedText = encryptedText.substring(0,encryptedText.length()-1);\r
398                         if (encryptedText.endsWith("\r"))\r
399                                 encryptedText = encryptedText.substring(0,encryptedText.length()-1);\r
400                         \r
401                         // Add the commands\r
402                         String hint = enmedia.attribute("hint");\r
403                         hint = hint.replace("'","&apos;");\r
404                         enmedia.setAttribute("onClick", "window.jambi.decryptText('crypt"+Global.cryptCounter.toString()+"', '"+encryptedText+"', '"+hint+"');");\r
405                         enmedia.setAttribute("onMouseOver", "style.cursor='hand'");\r
406                         enmedia.setTagName("img");\r
407                         enmedia.removeChild(enmedia.firstChild());   // Remove the actual encrypted text\r
408                 }\r
409 \r
410                 \r
411                 // Modify link tags\r
412                 anchors = docElem.elementsByTagName("a");\r
413                 enCryptLen = anchors.length();\r
414                 for (int i=0; i<anchors.length(); i++) {\r
415                         QDomElement element = anchors.at(i).toElement();\r
416                         if (!element.attribute("href").toLowerCase().startsWith("latex://"))\r
417                                 element.setAttribute("title", element.attribute("href"));\r
418                         else {\r
419                                 element.setAttribute("title", element.attribute("title").toLowerCase().replace("http://latex.codecogs.com/gif.latex?",""));\r
420                         }\r
421                 }\r
422 \r
423                 logger.log(logger.HIGH, "Leaving NeverNote.modifyTags");\r
424                 return doc;\r
425         }\r
426         \r
427 \r
428         // Get an ink note image.  If an image doesn't exist then we fall back \r
429         // to the old ugly icon\r
430     private boolean buildInkNote(QDomDocument doc, QDomElement docElem, QDomElement enmedia, QDomAttr hash, String appl) {\r
431         String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNote.getGuid(), hash.value());\r
432         Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid, false);\r
433  \r
434         // If we can't find the resource, then fall back to the old method.  We'll return & show\r
435         // an error later\r
436         if (r == null || r.getData() == null) \r
437                 return false;\r
438         \r
439         // If there isn't some type of error, continue on.\r
440                 if (!resourceError) {\r
441                         \r
442                         // Get a list of images in the database.  We'll use these to bulid the page.\r
443                         List<QByteArray> data = conn.getInkImagesTable().getImage(r.getGuid());\r
444                         \r
445                         // If no pictures are found, go back to & just show the icon\r
446                         if (data.size() == 0)\r
447                                 return false;\r
448                         \r
449                         // We have pictures, so append them to the page.  This really isn't proper since\r
450                         // we leave the en-media tag in place, but since we can't edit the page it doesn't\r
451                         // hurt anything.\r
452                         for (int i=0; i<data.size(); i++) {\r
453                         QFile f = new QFile(Global.getFileManager().getResDirPath(resGuid + new Integer(i).toString()+".png"));\r
454                                 f.open(OpenModeFlag.WriteOnly);\r
455                                 f.write(data.get(i));\r
456                                 f.close();\r
457                                 QDomElement newImage = doc.createElement("img");\r
458                                 newImage.setAttribute("src", QUrl.fromLocalFile(f.fileName()).toString());\r
459                                 enmedia.appendChild(newImage);\r
460                         }\r
461                         return true;\r
462                 }\r
463         return false;\r
464     }\r
465         \r
466         \r
467     // Modify the en-media tag into an attachment\r
468     private void modifyApplicationTags(QDomDocument doc, QDomElement docElem, QDomElement enmedia, QDomAttr hash, String appl) {\r
469         logger.log(logger.HIGH, "Entering NeverNote.modifyApplicationTags");\r
470         if (appl.equalsIgnoreCase("vnd.evernote.ink")) {\r
471                 inkNote = true;\r
472             if (buildInkNote(doc, docElem, enmedia, hash, appl))\r
473                 return;\r
474         }\r
475         String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNote.getGuid(), hash.value());\r
476         Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid, false);\r
477         if (r == null || r.getData() == null) \r
478                 resourceError = true;\r
479                 if (r!= null) {\r
480                         if (r.getData()!=null) {\r
481                                 // Did we get a generic applicaiton?  Then look at the file name to \r
482                                 // try and find a good application type for the icon\r
483                                 if (appl.equalsIgnoreCase("octet-stream")) {\r
484                                         if (r.getAttributes() != null && r.getAttributes().getFileName() != null) {\r
485                                                 String fn = r.getAttributes().getFileName();\r
486                                                 int pos = fn.lastIndexOf(".");\r
487                                                 if (pos > -1) {\r
488                                                         appl = fn.substring(pos+1);\r
489                                                 }\r
490                                         }\r
491                                 }\r
492                                 \r
493                                 String fileDetails = null;\r
494                                 if (r.getAttributes() != null && r.getAttributes().getFileName() != null && !r.getAttributes().getFileName().equals(""))\r
495                                         fileDetails = r.getAttributes().getFileName();\r
496                                 String contextFileName;\r
497                                 FileManager fileManager = Global.getFileManager();\r
498                 if (fileDetails != null && !fileDetails.equals("")) {\r
499                         if (!noteHistory) {\r
500                                 enmedia.setAttribute("href", "nnres://" +r.getGuid() \r
501                                                 +Global.attachmentNameDelimeter +fileDetails);\r
502                                 contextFileName = fileManager.getResDirPath(r.getGuid() \r
503                                                 +Global.attachmentNameDelimeter + fileDetails);\r
504                         } else {\r
505                                 enmedia.setAttribute("href", "nnres://" +r.getGuid() + currentNote.getUpdateSequenceNum() \r
506                                                 +Global.attachmentNameDelimeter +fileDetails);\r
507                                 contextFileName = fileManager.getResDirPath(r.getGuid() + currentNote.getUpdateSequenceNum() \r
508                                                 +Global.attachmentNameDelimeter + fileDetails);\r
509                         }\r
510                                 } else { \r
511                                         if (!noteHistory) {\r
512                                                 enmedia.setAttribute("href", "nnres://" +r.getGuid() +currentNote.getUpdateSequenceNum()\r
513                                                                 +Global.attachmentNameDelimeter +appl);\r
514                                                 contextFileName = fileManager.getResDirPath(r.getGuid() +currentNote.getUpdateSequenceNum() \r
515                                                                 +Global.attachmentNameDelimeter + appl);\r
516                                         } else {\r
517                                                 enmedia.setAttribute("href", "nnres://" +r.getGuid() \r
518                                                                 +Global.attachmentNameDelimeter +appl);\r
519                                                 contextFileName = fileManager.getResDirPath(r.getGuid() \r
520                                                                 +Global.attachmentNameDelimeter + appl);\r
521                                         }\r
522                                 }\r
523                                 contextFileName = contextFileName.replace("\\", "/");\r
524                                 enmedia.setAttribute("onContextMenu", "window.jambi.resourceContextMenu('" +contextFileName +"');");\r
525                                 if (fileDetails == null || fileDetails.equals(""))\r
526                                         fileDetails = "";\r
527                                 enmedia.setAttribute("en-tag", "en-media");\r
528                                 enmedia.setAttribute("guid", r.getGuid());\r
529                                 enmedia.setTagName("a");\r
530                                 QDomElement newText = doc.createElement("img");\r
531                                 boolean goodPreview = false;\r
532                                 String filePath = "";\r
533                                 if (appl.equalsIgnoreCase("pdf") && pdfPreview) {\r
534                                         String fileName;\r
535                                         Resource res = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);\r
536                                         if (res.getAttributes() != null && \r
537                                                         res.getAttributes().getFileName() != null && \r
538                                                         !res.getAttributes().getFileName().trim().equals(""))\r
539                                                 fileName = res.getGuid()+Global.attachmentNameDelimeter+res.getAttributes().getFileName();\r
540                                         else\r
541                                                 fileName = res.getGuid()+".pdf";\r
542                                         QFile file = new QFile(fileManager.getResDirPath(fileName));\r
543                                 QFile.OpenMode mode = new QFile.OpenMode();\r
544                                 mode.set(QFile.OpenModeFlag.WriteOnly);\r
545                                 file.open(mode);\r
546                                 QDataStream out = new QDataStream(file);\r
547                                 Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(res.getGuid(), true);\r
548                                         QByteArray binData = new QByteArray(resBinary.getData().getBody());\r
549                                         resBinary = null;\r
550                                 out.writeBytes(binData.toByteArray());\r
551                                 file.close();\r
552                                 PDFPreview pdfPreview = new PDFPreview();\r
553                                         goodPreview = pdfPreview.setupPreview(file.fileName(), appl,0);\r
554                                         if (goodPreview) {\r
555                                                 QDomElement span = doc.createElement("span");\r
556                                                 QDomElement table = doc.createElement("table");\r
557                                                 span.setAttribute("pdfNavigationTable", "true");\r
558                                                 QDomElement tr = doc.createElement("tr");\r
559                                                 QDomElement td = doc.createElement("td");\r
560                                                 QDomElement left = doc.createElement("img");\r
561                                                 left.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");\r
562                                                 left.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");\r
563                                                 left.setAttribute("onMouseOver", "style.cursor='hand'");\r
564                                                 QDomElement right = doc.createElement("img");\r
565                                                 right.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");\r
566                                                 left.setAttribute("onMouseDown", "window.jambi.previousPage('" +file.fileName() +"')");\r
567                                                 // NFC TODO: should these be file:// URLs?\r
568                                                 left.setAttribute("src", Global.getFileManager().getImageDirPath("small_left.png"));\r
569                                                 right.setAttribute("src", Global.getFileManager().getImageDirPath("small_right.png"));\r
570                                                 right.setAttribute("onMouseOver", "style.cursor='hand'");\r
571                                                 \r
572                                                 table.appendChild(tr);\r
573                                                 tr.appendChild(td);\r
574                                                 td.appendChild(left);\r
575                                                 td.appendChild(right);\r
576                                                 span.appendChild(table);\r
577                                                 enmedia.parentNode().insertBefore(span, enmedia);\r
578                                         } \r
579                                         filePath = fileName+".png";\r
580                                 }\r
581                                 String icon = findIcon(appl);\r
582                                 if (icon.equals("attachment.png"))\r
583                                         icon = findIcon(fileDetails.substring(fileDetails.indexOf(".")+1));\r
584                                 // NFC TODO: should this be a 'file://' URL?\r
585                                 newText.setAttribute("src", Global.getFileManager().getImageDirPath(icon));\r
586                                 if (goodPreview) {\r
587                                 // NFC TODO: should this be a 'file://' URL?\r
588                                         newText.setAttribute("src", fileManager.getResDirPathSpecialChar(filePath));\r
589                                         newText.setAttribute("style", "border-style:solid; border-color:green; padding:0.5mm 0.5mm 0.5mm 0.5mm;");\r
590                                 }\r
591                                 newText.setAttribute("title", fileDetails);\r
592                                 enmedia.removeChild(enmedia.firstChild());\r
593                                 \r
594                                 enmedia.appendChild(newText);\r
595                         }\r
596                 }\r
597                 logger.log(logger.HIGH, "Leaving NeverNote.modifyApplicationTags");\r
598     }\r
599     // Modify the en-to tag into an input field\r
600     private void modifyTodoTags(QDomElement todo) {\r
601         logger.log(logger.HIGH, "Entering NeverNote.modifyTodoTags");\r
602                 todo.setAttribute("type", "checkbox");\r
603                 String checked = todo.attribute("checked");\r
604                 todo.removeAttribute("checked");\r
605                 if (checked.equalsIgnoreCase("true"))\r
606                         todo.setAttribute("checked", "");\r
607                 else\r
608                         todo.setAttribute("unchecked","");\r
609                 todo.setAttribute("value", checked);\r
610                 todo.setAttribute("onClick", "value=checked;window.jambi.contentChanged(); ");\r
611                 todo.setAttribute("onMouseOver", "style.cursor='hand'");\r
612                 todo.setTagName("input");\r
613                 logger.log(logger.HIGH, "Leaving NeverNote.modifyTodoTags");\r
614     }\r
615     \r
616     \r
617     \r
618     // Modify any cached todo tags that may have changed\r
619     public String modifyCachedTodoTags(String note) {\r
620         logger.log(logger.HIGH, "Entering NeverNote.modifyCachedTodoTags");\r
621         StringBuffer html = new StringBuffer(note);\r
622                 for (int i=html.indexOf("<input", 0); i>-1; i=html.indexOf("<input", i)) {\r
623                         int endPos =html.indexOf(">",i+1);\r
624                         String input = html.substring(i,endPos);\r
625                         if (input.indexOf("value=\"true\"") > 0) \r
626                                 input = input.replace(" unchecked=\"\"", " checked=\"\"");\r
627                         else\r
628                                 input = input.replace(" checked=\"\"", " unchecked=\"\"");\r
629                         html.replace(i, endPos, input);\r
630                         i++;\r
631                 }\r
632                 logger.log(logger.HIGH, "Leaving NeverNote.modifyCachedTodoTags");\r
633                 return html.toString();\r
634     }\r
635     \r
636     \r
637 \r
638 \r
639         // Scan and do hilighting of words\r
640         public QDomDocument addHilight(QDomDocument doc) {\r
641 //              EnSearch e = listManager.getEnSearch();\r
642                 if (enSearch.hilightWords == null || enSearch.hilightWords.size() == 0)\r
643                         return doc;\r
644                 XMLInsertHilight hilight = new XMLInsertHilight(doc, enSearch.hilightWords);\r
645                 return hilight.getDoc();\r
646         }\r
647         \r
648         \r
649     // find the appropriate icon for an attachment\r
650     private String findIcon(String appl) {\r
651         logger.log(logger.HIGH, "Entering NeverNote.findIcon");\r
652         appl = appl.toLowerCase();\r
653         String relativePath = appl + ".png";\r
654         File f = Global.getFileManager().getImageDirFile(relativePath);\r
655         if (f.exists()) {\r
656             return relativePath;\r
657         }\r
658         if (f.exists())\r
659                 return appl+".png";\r
660         logger.log(logger.HIGH, "Leaving NeverNote.findIcon");\r
661         return "attachment.png";\r
662     }\r
663 \r
664 }\r