xesam.el 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. ;;; xesam.el --- Xesam interface to search engines.
  2. ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
  3. ;; Author: Michael Albinus <michael.albinus@gmx.de>
  4. ;; Keywords: tools, hypermedia
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; This package provides an interface to Xesam, a D-Bus based "eXtEnsible
  18. ;; Search And Metadata specification". It has been tested with
  19. ;;
  20. ;; xesam-glib 0.3.4, xesam-tools 0.6.1
  21. ;; beagle 0.3.7, beagle-xesam 0.2
  22. ;; strigi 0.5.11
  23. ;; The precondition for this package is a D-Bus aware Emacs. This is
  24. ;; configured per default, when Emacs is built on a machine running
  25. ;; D-Bus. Furthermore, there must be at least one search engine
  26. ;; running, which supports the Xesam interface. Beagle and strigi have
  27. ;; been tested; tracker, pinot and recoll are also said to support
  28. ;; Xesam. You can check the existence of such a search engine by
  29. ;;
  30. ;; (dbus-list-queued-owners :session "org.freedesktop.xesam.searcher")
  31. ;; In order to start a search, you must load xesam.el:
  32. ;;
  33. ;; (require 'xesam)
  34. ;; xesam.el supports two types of queries, which are explained *very* short:
  35. ;;
  36. ;; * Full text queries. Just search keys shall be given, like
  37. ;;
  38. ;; hello world
  39. ;;
  40. ;; A full text query in xesam.el is restricted to files.
  41. ;;
  42. ;; * Xesam End User Search Language queries. The Xesam query language
  43. ;; is described at <http://xesam.org/main/XesamUserSearchLanguage>,
  44. ;; which must be consulted for the whole features.
  45. ;;
  46. ;; A query string consists of search keys, collectors, selectors,
  47. ;; and phrases. Search keys are words like in a full text query:
  48. ;;
  49. ;; hello word
  50. ;;
  51. ;; A selector is a tuple <keyword><relation>. <keyword> can be any
  52. ;; predefined Xesam keyword, the most common keywords are "ext"
  53. ;; (file name extension), "format " (mime type), "tag" (user
  54. ;; keywords) and "type" (types of items, like "audio", "file",
  55. ;; "picture", "attachment"). <relation> is a comparison to a value,
  56. ;; which must be a string (relation ":" or "=") or number (relation
  57. ;; "<=", ">=", "<", ">"):
  58. ;;
  59. ;; type:attachment ext=el
  60. ;;
  61. ;; A collector is one of the items "AND", "and", "&&", "OR", "or",
  62. ;; "||", or "-". The default collector on multiple terms is "AND";
  63. ;; "-" means "AND NOT".
  64. ;;
  65. ;; albinus -type:file
  66. ;;
  67. ;; A phrase is a string enclosed in quotes, with appended modifiers
  68. ;; (single letters). Examples of modifiers are "c" (case
  69. ;; sensitive), "C" (case insensitive), "e" (exact match), "r"
  70. ;; (regular expression):
  71. ;;
  72. ;; "Hello world"c
  73. ;; You can customize, whether you want to apply a Xesam user query, or
  74. ;; a full text query. Note, that not every search engine supports
  75. ;; both query types.
  76. ;;
  77. ;; (setq xesam-query-type 'fulltext-query)
  78. ;;
  79. ;; Another option to be customized is the number of hits to be
  80. ;; presented at once.
  81. ;;
  82. ;; (setq xesam-hits-per-page 50)
  83. ;; A search can be started by the command
  84. ;;
  85. ;; M-x xesam-search
  86. ;;
  87. ;; When several search engines are registered, the engine to be used
  88. ;; can be selected via minibuffer completion. Afterwards, the query
  89. ;; shall be entered in the minibuffer.
  90. ;; Search results are presented in a new buffer. This buffer has the
  91. ;; major mode `xesam-mode', with the following keybindings:
  92. ;; SPC `scroll-up'
  93. ;; DEL `scroll-down'
  94. ;; < `beginning-of-buffer'
  95. ;; > `end-of-buffer'
  96. ;; q `quit-window'
  97. ;; z `kill-this-buffer'
  98. ;; g `revert-buffer'
  99. ;; The search results are represented by widgets. Navigation commands
  100. ;; are the usual widget navigation commands:
  101. ;; TAB `widget-forward'
  102. ;; <backtab> `widget-backward'
  103. ;; Applying RET, <down-mouse-1>, or <down-mouse-2> on a URL belonging
  104. ;; to the widget, brings up more details of the search hit. The way,
  105. ;; how this hit is presented, depends on the type of the hit. HTML
  106. ;; files are opened via `browse-url'. Local files are opened in a new
  107. ;; buffer, with highlighted search hits (highlighting can be toggled
  108. ;; by `xesam-minor-mode' in that buffer).
  109. ;;; Code:
  110. ;; D-Bus support in the Emacs core can be disabled with configuration
  111. ;; option "--without-dbus". Declare used subroutines and variables.
  112. (declare-function dbus-call-method "dbusbind.c")
  113. (declare-function dbus-register-signal "dbusbind.c")
  114. (require 'dbus)
  115. ;; Pacify byte compiler.
  116. (eval-when-compile
  117. (require 'cl))
  118. ;; Widgets are used to highlight the search results.
  119. (require 'widget)
  120. (require 'wid-edit)
  121. ;; `run-at-time' is used in the signal handler.
  122. (require 'timer)
  123. ;; The default search field is "xesam:url". It must be inspected.
  124. (require 'url)
  125. (defgroup xesam nil
  126. "Xesam compatible interface to search engines."
  127. :group 'extensions
  128. :group 'comm
  129. :version "23.1")
  130. (defcustom xesam-query-type 'user-query
  131. "Xesam query language type."
  132. :group 'xesam
  133. :type '(choice
  134. (const :tag "Xesam user query" user-query)
  135. (const :tag "Xesam fulltext query" fulltext-query)))
  136. (defcustom xesam-hits-per-page 20
  137. "Number of search hits to be displayed in the result buffer."
  138. :group 'xesam
  139. :type 'integer)
  140. (defface xesam-mode-line '((t :inherit mode-line-emphasis))
  141. "Face to highlight mode line."
  142. :group 'xesam)
  143. (defface xesam-highlight '((t :inherit match))
  144. "Face to highlight query entries.
  145. It will be overlaid by `widget-documentation-face', so it shall
  146. be different at least in one face property not set in that face."
  147. :group 'xesam)
  148. (defvar xesam-debug nil
  149. "Insert debug information in the help echo.")
  150. (defconst xesam-service-search "org.freedesktop.xesam.searcher"
  151. "The D-Bus name used to talk to Xesam.")
  152. (defconst xesam-path-search "/org/freedesktop/xesam/searcher/main"
  153. "The D-Bus object path used to talk to Xesam.")
  154. ;; Methods: "NewSession", "SetProperty", "GetProperty",
  155. ;; "CloseSession", "NewSearch", "StartSearch", "GetHitCount",
  156. ;; "GetHits", "GetHitData", "CloseSearch" and "GetState".
  157. ;; Signals: "HitsAdded", "HitsRemoved", "HitsModified", "SearchDone"
  158. ;; and "StateChanged".
  159. (defconst xesam-interface-search "org.freedesktop.xesam.Search"
  160. "The D-Bus Xesam search interface.")
  161. (defconst xesam-all-fields
  162. '("xesam:35mmEquivalent" "xesam:aimContactMedium" "xesam:aperture"
  163. "xesam:aspectRatio" "xesam:attachmentEncoding" "xesam:attendee"
  164. "xesam:audioBitrate" "xesam:audioChannels" "xesam:audioCodec"
  165. "xesam:audioCodecType" "xesam:audioSampleFormat" "xesam:audioSampleRate"
  166. "xesam:author" "xesam:bcc" "xesam:birthDate" "xesam:blogContactURL"
  167. "xesam:cameraManufacturer" "xesam:cameraModel" "xesam:cc" "xesam:ccdWidth"
  168. "xesam:cellPhoneNumber" "xesam:characterCount" "xesam:charset"
  169. "xesam:colorCount" "xesam:colorSpace" "xesam:columnCount" "xesam:comment"
  170. "xesam:commentCharacterCount" "xesam:conflicts" "xesam:contactMedium"
  171. "xesam:contactName" "xesam:contactNick" "xesam:contactPhoto"
  172. "xesam:contactURL" "xesam:contains" "xesam:contenKeyword"
  173. "xesam:contentComment" "xesam:contentCreated" "xesam:contentModified"
  174. "xesam:contentType" "xesam:contributor" "xesam:copyright" "xesam:creator"
  175. "xesam:definesClass" "xesam:definesFunction" "xesam:definesGlobalVariable"
  176. "xesam:deletionTime" "xesam:depends" "xesam:description" "xesam:device"
  177. "xesam:disclaimer" "xesam:documentCategory" "xesam:duration"
  178. "xesam:emailAddress" "xesam:eventEnd" "xesam:eventLocation"
  179. "xesam:eventStart" "xesam:exposureBias" "xesam:exposureProgram"
  180. "xesam:exposureTime" "xesam:faxPhoneNumber" "xesam:fileExtension"
  181. "xesam:fileSystemType" "xesam:flashUsed" "xesam:focalLength"
  182. "xesam:focusDistance" "xesam:formatSubtype" "xesam:frameCount"
  183. "xesam:frameRate" "xesam:freeSpace" "xesam:gender" "xesam:generator"
  184. "xesam:generatorOptions" "xesam:group" "xesam:hash" "xesam:hash"
  185. "xesam:height" "xesam:homeEmailAddress" "xesam:homePhoneNumber"
  186. "xesam:homePostalAddress" "xesam:homepageContactURL"
  187. "xesam:horizontalResolution" "xesam:icqContactMedium" "xesam:id"
  188. "xesam:imContactMedium" "xesam:interests" "xesam:interlaceMode"
  189. "xesam:isEncrypted" "xesam:isImportant" "xesam:isInProgress"
  190. "xesam:isPasswordProtected" "xesam:isRead" "xesam:isoEquivalent"
  191. "xesam:jabberContactMedium" "xesam:keyword" "xesam:language" "xesam:legal"
  192. "xesam:license" "xesam:licenseType" "xesam:lineCount" "xesam:links"
  193. "xesam:mailingPostalAddress" "xesam:maintainer" "xesam:md5Hash"
  194. "xesam:mediaCodec" "xesam:mediaCodecBitrate" "xesam:mediaCodecType"
  195. "xesam:meteringMode" "xesam:mimeType" "xesam:mountPoint"
  196. "xesam:msnContactMedium" "xesam:name" "xesam:occupiedSpace"
  197. "xesam:orientation" "xesam:originalLocation" "xesam:owner"
  198. "xesam:pageCount" "xesam:permissions" "xesam:phoneNumber"
  199. "xesam:physicalAddress" "xesam:pixelFormat" "xesam:primaryRecipient"
  200. "xesam:programmingLanguage" "xesam:rating" "xesam:receptionTime"
  201. "xesam:recipient" "xesam:related" "xesam:remoteUser" "xesam:rowCount"
  202. "xesam:sampleBitDepth" "xesam:sampleFormat" "xesam:secondaryRecipient"
  203. "xesam:sha1Hash" "xesam:size" "xesam:skypeContactMedium"
  204. "xesam:sourceCreated" "xesam:sourceModified" "xesam:storageSize"
  205. "xesam:subject" "xesam:supercedes" "xesam:title" "xesam:to"
  206. "xesam:totalSpace" "xesam:totalUncompressedSize" "xesam:url"
  207. "xesam:usageIntensity" "xesam:userComment" "xesam:userKeyword"
  208. "xesam:uuid" "xesam:version" "xesam:verticalResolution"
  209. "xesam:videoBitrate"
  210. "xesam:videoCodec" "xesam:videoCodecType" "xesam:whiteBalance"
  211. "xesam:width" "xesam:wordCount" "xesam:workEmailAddress"
  212. "xesam:workPhoneNumber" "xesam:workPostalAddress"
  213. "xesam:yahooContactMedium")
  214. "All fields from the Xesam Core Ontology.
  215. This defconst can be used to check for a new search engine, which
  216. fields are supported.")
  217. (defconst xesam-user-query
  218. "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
  219. <request xmlns=\"http://freedesktop.org/standards/xesam/1.0/query\">
  220. <userQuery>
  221. %s
  222. </userQuery>
  223. </request>"
  224. "The Xesam user query XML.")
  225. (defconst xesam-fulltext-query
  226. "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
  227. <request xmlns=\"http://freedesktop.org/standards/xesam/1.0/query\">
  228. <query content=\"xesam:Document\" source=\"xesam:File\">
  229. <fullText>
  230. <string>%s</string>
  231. </fullText>
  232. </query>
  233. </request>"
  234. "The Xesam fulltext query XML.")
  235. (declare-function dbus-get-unique-name "dbusbind.c" (bus))
  236. (defvar xesam-dbus-unique-names
  237. (list (cons :system (dbus-get-unique-name :system))
  238. (cons :session (dbus-get-unique-name :session)))
  239. "The unique names, under which Emacs is registered at D-Bus.")
  240. (defun xesam-dbus-call-method (&rest args)
  241. "Apply a D-Bus method call.
  242. `dbus-call-method' is preferred, because it performs better.
  243. If the target D-Bus service is owned by Emacs, this
  244. is not applicable, and `dbus-call-method-non-blocking' must be
  245. used instead. ARGS are identical to the argument list of both
  246. functions."
  247. (apply
  248. ;; The first argument is the bus, the second argument the targt service.
  249. (if (string-equal (cdr (assoc (car args) xesam-dbus-unique-names))
  250. (cadr args))
  251. 'dbus-call-method-non-blocking 'dbus-call-method)
  252. args))
  253. (defun xesam-get-property (engine property)
  254. "Return the PROPERTY value of ENGINE."
  255. ;; "GetProperty" returns a variant, so we must use the car.
  256. (car (xesam-dbus-call-method
  257. :session (car engine) xesam-path-search
  258. xesam-interface-search "GetProperty"
  259. (xesam-get-cached-property engine "session") property)))
  260. (defun xesam-set-property (engine property value)
  261. "Set the PROPERTY of ENGINE to VALUE.
  262. VALUE can be a string, a non-negative integer, a boolean
  263. value (nil or t), or a list of them. It returns the new value of
  264. PROPERTY in the search engine. This new value can be different
  265. from VALUE, depending on what the search engine accepts."
  266. ;; "SetProperty" returns a variant, so we must use the car.
  267. (car (xesam-dbus-call-method
  268. :session (car engine) xesam-path-search
  269. xesam-interface-search "SetProperty"
  270. (xesam-get-cached-property engine "session") property
  271. ;; The value must be a variant. It can be only a string, an
  272. ;; unsigned int, a boolean, or an array of them. So we need
  273. ;; no type keyword; we let the type check to the search
  274. ;; engine.
  275. (list :variant value))))
  276. (defvar xesam-minibuffer-vendor-history nil
  277. "Interactive vendor history.")
  278. (defvar xesam-minibuffer-query-history nil
  279. "Interactive query history.")
  280. ;; Pacify byte compiler.
  281. (defvar xesam-vendor nil)
  282. (make-variable-buffer-local 'xesam-vendor)
  283. (put 'xesam-vendor 'permanent-local t)
  284. (defvar xesam-engine nil)
  285. (defvar xesam-search nil)
  286. (defvar xesam-type nil)
  287. (defvar xesam-query nil)
  288. (defvar xesam-xml-string nil)
  289. (defvar xesam-objects nil)
  290. (defvar xesam-current nil)
  291. (defvar xesam-count nil)
  292. (defvar xesam-to nil)
  293. (defvar xesam-notify-function nil)
  294. (defvar xesam-refreshing nil)
  295. ;;; Search engines.
  296. (defvar xesam-search-engines nil
  297. "List of available Xesam search engines.
  298. Every entry is an association list, with a car denoting the
  299. unique D-Bus service name of the engine. The rest of the entry
  300. are cached associations of engine attributes, like the session
  301. identifier, and the display name. Example:
  302. \(\(\":1.59\"
  303. \(\"session\" . \"0t1214948020ut358230u0p2698r3912347765k3213849828\")
  304. \(\"vendor.display\" . \"Tracker Xesam Service\"))
  305. \(\":1.27\"
  306. \(\"session\" . \"strigisession1369133069\")
  307. \(\"vendor.display\" . \"Strigi Desktop Search\")))
  308. A Xesam-compatible search engine is identified as a queued D-Bus
  309. service of the known service `xesam-service-search'.")
  310. (defun xesam-get-cached-property (engine property)
  311. "Return the PROPERTY value of ENGINE from the cache.
  312. If PROPERTY is not existing, retrieve it from ENGINE first."
  313. ;; If the property has not been cached yet, we retrieve it from the
  314. ;; engine, and cache it.
  315. (unless (assoc property engine)
  316. (xesam-set-cached-property
  317. engine property (xesam-get-property engine property)))
  318. (cdr (assoc property engine)))
  319. (defun xesam-set-cached-property (engine property value)
  320. "Set the PROPERTY of ENGINE to VALUE in the cache."
  321. (setcdr engine (append (cdr engine) (list (cons property value)))))
  322. (defun xesam-delete-search-engine (&rest args)
  323. "Remove service from `xesam-search-engines'."
  324. (setq xesam-search-engines
  325. (delete (assoc (car args) xesam-search-engines) xesam-search-engines)))
  326. (defvar dbus-debug)
  327. (defun xesam-search-engines ()
  328. "Return Xesam search engines, stored in `xesam-search-engines'.
  329. The first search engine is the name owner of `xesam-service-search'.
  330. If there is no registered search engine at all, the function returns `nil'."
  331. (let ((services (dbus-ignore-errors
  332. (dbus-list-queued-owners
  333. :session xesam-service-search)))
  334. engine vendor-id hit-fields)
  335. (dolist (service services)
  336. (unless (assoc-string service xesam-search-engines)
  337. ;; Open a new session, and add it to the search engines list.
  338. (add-to-list 'xesam-search-engines (list service) 'append)
  339. (setq engine (assoc service xesam-search-engines))
  340. ;; Add the session string.
  341. (xesam-set-cached-property
  342. engine "session"
  343. (xesam-dbus-call-method
  344. :session service xesam-path-search
  345. xesam-interface-search "NewSession"))
  346. ;; Unset the "search.live" property; we don't want to be
  347. ;; informed by changed results.
  348. (xesam-set-property engine "search.live" nil)
  349. ;; Check the vendor properties.
  350. (setq vendor-id (xesam-get-property engine "vendor.id")
  351. hit-fields (xesam-get-property engine "hit.fields"))
  352. ;; Usually, `hit.fields' shall describe supported fields.
  353. ;; That is not the case now, so we set it ourselves.
  354. ;; Hopefully, this will change later.
  355. (setq hit-fields
  356. (case (intern vendor-id)
  357. (Beagle
  358. '("xesam:mimeType" "xesam:url"))
  359. (Strigi
  360. '("xesam:author" "xesam:cc" "xesam:charset"
  361. "xesam:contentType" "xesam:fileExtension"
  362. "xesam:id" "xesam:lineCount" "xesam:links"
  363. "xesam:mimeType" "xesam:name" "xesam:size"
  364. "xesam:sourceModified" "xesam:subject" "xesam:to"
  365. "xesam:url"))
  366. (TrackerXesamSession
  367. '("xesam:relevancyRating" "xesam:url"))
  368. (Debbugs
  369. '("xesam:keyword" "xesam:owner" "xesam:title"
  370. "xesam:url" "xesam:sourceModified" "xesam:mimeType"
  371. "debbugs:key"))
  372. ;; xesam-tools yahoo service.
  373. (t '("xesam:contentModified" "xesam:mimeType" "xesam:summary"
  374. "xesam:title" "xesam:url" "yahoo:displayUrl"))))
  375. (xesam-set-property engine "hit.fields" hit-fields)
  376. (xesam-set-property engine "hit.fields.extended" '("xesam:snippet"))
  377. ;; Let us notify, when the search engine disappears.
  378. (dbus-register-signal
  379. :session dbus-service-dbus dbus-path-dbus
  380. dbus-interface-dbus "NameOwnerChanged"
  381. 'xesam-delete-search-engine service))))
  382. xesam-search-engines)
  383. ;;; Search buffers.
  384. (defvar xesam-mode-map
  385. (let ((map (copy-keymap special-mode-map)))
  386. (set-keymap-parent xesam-mode-map widget-keymap)
  387. map))
  388. (define-derived-mode xesam-mode special-mode "Xesam"
  389. "Major mode for presenting search results of a Xesam search.
  390. In this mode, widgets represent the search results.
  391. \\{xesam-mode-map}
  392. Turning on Xesam mode runs the normal hook `xesam-mode-hook'. It
  393. can be used to set `xesam-notify-function', which must a search
  394. engine specific, widget :notify function to visualize xesam:url."
  395. (set (make-local-variable 'xesam-notify-function) nil)
  396. ;; Maybe we implement something useful, later on.
  397. (set (make-local-variable 'revert-buffer-function) 'ignore)
  398. ;; `xesam-engine', `xesam-search', `xesam-type', `xesam-query', and
  399. ;; `xesam-xml-string' will be set in `xesam-new-search'.
  400. (set (make-local-variable 'xesam-engine) nil)
  401. (set (make-local-variable 'xesam-search) nil)
  402. (set (make-local-variable 'xesam-type) "")
  403. (set (make-local-variable 'xesam-query) "")
  404. (set (make-local-variable 'xesam-xml-string) "")
  405. (set (make-local-variable 'xesam-objects) nil)
  406. ;; `xesam-current' is the last hit put into the search buffer,
  407. (set (make-local-variable 'xesam-current) 0)
  408. ;; `xesam-count' is the number of hits reported by the search engine.
  409. (set (make-local-variable 'xesam-count) 0)
  410. ;; `xesam-to' is the upper hit number to be presented.
  411. (set (make-local-variable 'xesam-to) xesam-hits-per-page)
  412. ;; `xesam-notify-function' can be a search engine specific function
  413. ;; to visualize xesam:url. It can be overwritten in `xesam-mode'.
  414. (set (make-local-variable 'xesam-notify-function) nil)
  415. ;; `xesam-refreshing' is an indicator, whether the buffer is just
  416. ;; being updated. Needed, because `xesam-refresh-search-buffer'
  417. ;; can be triggered by an event.
  418. (set (make-local-variable 'xesam-refreshing) nil)
  419. ;; Mode line position returns hit counters.
  420. (set (make-local-variable 'mode-line-position)
  421. (list '(-3 "%p%")
  422. '(10 (:eval (format " (%d/%d)" xesam-current xesam-count)))))
  423. ;; Header line contains the query string.
  424. (set (make-local-variable 'header-line-format)
  425. (list '(20
  426. (:eval
  427. (list "Type: "
  428. (propertize xesam-type 'face 'xesam-mode-line))))
  429. '(10
  430. (:eval
  431. (list " Query: "
  432. (propertize
  433. xesam-query
  434. 'face 'xesam-mode-line
  435. 'help-echo (when xesam-debug xesam-xml-string)))))))
  436. (when (not (called-interactively-p 'interactive))
  437. ;; Initialize buffer.
  438. (setq buffer-read-only t)
  439. (let ((inhibit-read-only t))
  440. (erase-buffer))))
  441. ;; It doesn't make sense to call it interactively.
  442. (put 'xesam-mode 'disabled t)
  443. ;; The very first buffer created with `xesam-mode' does not have the
  444. ;; keymap etc. So we create a dummy buffer. Stupid.
  445. (with-temp-buffer (xesam-mode))
  446. (define-minor-mode xesam-minor-mode
  447. "Toggle Xesam minor mode.
  448. With a prefix argument ARG, enable Xesam minor mode if ARG is
  449. positive, and disable it otherwise. If called from Lisp, enable
  450. the mode if ARG is omitted or nil.
  451. When Xesam minor mode is enabled, all text which matches a
  452. previous Xesam query in this buffer is highlighted."
  453. :group 'xesam
  454. :init-value nil
  455. :lighter " Xesam"
  456. (when (local-variable-p 'xesam-query)
  457. ;; Run only if the buffer is related to a Xesam search.
  458. (save-excursion
  459. (if xesam-minor-mode
  460. ;; Highlight hits.
  461. (let ((query-regexp (regexp-opt (split-string xesam-query nil t) t))
  462. (case-fold-search t))
  463. ;; I have no idea whether people will like setting
  464. ;; `isearch-case-fold-search' and `query-regexp'. Maybe
  465. ;; this shall be controlled by a custom option.
  466. (unless isearch-case-fold-search (isearch-toggle-case-fold))
  467. (isearch-update-ring query-regexp t)
  468. ;; Create overlays.
  469. (goto-char (point-min))
  470. (while (re-search-forward query-regexp nil t)
  471. (overlay-put
  472. (make-overlay
  473. (match-beginning 0) (match-end 0)) 'face 'xesam-highlight)))
  474. ;; Remove overlays.
  475. (dolist (ov (overlays-in (point-min) (point-max)))
  476. (delete-overlay ov))))))
  477. (defun xesam-buffer-name (service search)
  478. "Return the buffer name where to present search results.
  479. SERVICE is the D-Bus unique service name of the Xesam search engine.
  480. SEARCH is the search identification in that engine. Both must be strings."
  481. (format "*%s/%s*" service search))
  482. (defun xesam-highlight-string (string)
  483. "Highlight text enclosed by <b> and </b>.
  484. Return propertized STRING."
  485. (while (string-match "\\(.*\\)\\(<b>\\)\\(.*\\)\\(</b>\\)\\(.*\\)" string)
  486. (setq string
  487. (format
  488. "%s%s%s"
  489. (match-string 1 string)
  490. (propertize (match-string 3 string) 'face 'xesam-highlight)
  491. (match-string 5 string))))
  492. string)
  493. (defun xesam-refresh-entry (engine entry)
  494. "Refreshes one entry in the search buffer."
  495. (let* ((result (nth (1- xesam-current) xesam-objects))
  496. widget)
  497. ;; Create widget.
  498. (setq widget (widget-convert 'link))
  499. (when xesam-debug
  500. (widget-put widget :help-echo ""))
  501. ;; Take all results.
  502. (dolist (field (xesam-get-cached-property engine "hit.fields"))
  503. (when (cond
  504. ((stringp (caar result)) (not (zerop (length (caar result)))))
  505. ((numberp (caar result)) (not (zerop (caar result))))
  506. ((caar result) t))
  507. (when xesam-debug
  508. (widget-put
  509. widget :help-echo
  510. (format "%s%s: %s\n"
  511. (widget-get widget :help-echo) field (caar result))))
  512. (widget-put widget (intern (concat ":" field)) (caar result)))
  513. (setq result (cdr result)))
  514. ;; Strigi doesn't return URLs in xesam:url. We must fix this.
  515. (when
  516. (not (url-type (url-generic-parse-url (widget-get widget :xesam:url))))
  517. (widget-put
  518. widget :xesam:url (concat "file://" (widget-get widget :xesam:url))))
  519. ;; Strigi returns xesam:size as string. We must fix this.
  520. (when (and (widget-member widget :xesam:size)
  521. (stringp (widget-get widget :xesam:size)))
  522. (widget-put
  523. widget :xesam:size (string-to-number (widget-get widget :xesam:url))))
  524. ;; First line: :tag.
  525. (cond
  526. ((widget-member widget :xesam:title)
  527. (widget-put widget :tag (widget-get widget :xesam:title)))
  528. ((widget-member widget :xesam:subject)
  529. (widget-put widget :tag (widget-get widget :xesam:subject)))
  530. ((widget-member widget :xesam:mimeType)
  531. (widget-put widget :tag (widget-get widget :xesam:mimeType)))
  532. ((widget-member widget :xesam:name)
  533. (widget-put widget :tag (widget-get widget :xesam:name))))
  534. ;; Highlight the search items.
  535. (when (widget-member widget :tag)
  536. (widget-put
  537. widget :tag (xesam-highlight-string (widget-get widget :tag))))
  538. ;; Last Modified.
  539. (when (and (widget-member widget :xesam:sourceModified)
  540. (not
  541. (zerop
  542. (string-to-number (widget-get widget :xesam:sourceModified)))))
  543. (widget-put
  544. widget :tag
  545. (format
  546. "%s\nLast Modified: %s"
  547. (or (widget-get widget :tag) "")
  548. (format-time-string
  549. "%d %B %Y, %T"
  550. (seconds-to-time
  551. (string-to-number (widget-get widget :xesam:sourceModified)))))))
  552. ;; Second line: :value.
  553. (widget-put widget :value (widget-get widget :xesam:url))
  554. (cond
  555. ;; A search engine can set `xesam-notify-function' via
  556. ;; `xesam-mode-hooks'.
  557. (xesam-notify-function
  558. (widget-put widget :notify xesam-notify-function))
  559. ;; In case of HTML, we use a URL link.
  560. ((and (widget-member widget :xesam:mimeType)
  561. (string-equal "text/html" (widget-get widget :xesam:mimeType)))
  562. (setcar widget 'url-link))
  563. ;; For local files, we will open the file as default action.
  564. ((string-match "file"
  565. (url-type (url-generic-parse-url
  566. (widget-get widget :xesam:url))))
  567. (widget-put
  568. widget :notify
  569. (lambda (widget &rest ignore)
  570. (let ((query xesam-query))
  571. (find-file
  572. (url-filename (url-generic-parse-url (widget-value widget))))
  573. (set (make-local-variable 'xesam-query) query)
  574. (xesam-minor-mode 1))))
  575. (widget-put
  576. widget :value
  577. (url-filename (url-generic-parse-url (widget-get widget :xesam:url))))))
  578. ;; Third line: :doc.
  579. (cond
  580. ((widget-member widget :xesam:summary)
  581. (widget-put widget :doc (widget-get widget :xesam:summary)))
  582. ((widget-member widget :xesam:snippet)
  583. (widget-put widget :doc (widget-get widget :xesam:snippet))))
  584. (when (widget-member widget :doc)
  585. (with-temp-buffer
  586. (insert
  587. (xesam-highlight-string (widget-get widget :doc)))
  588. (fill-region-as-paragraph (point-min) (point-max))
  589. (widget-put widget :doc (buffer-string)))
  590. (widget-put widget :help-echo (widget-get widget :doc)))
  591. ;; Format the widget.
  592. (widget-put
  593. widget :format
  594. (format "%d. %s%%[%%v%%]\n%s\n" xesam-current
  595. (if (widget-member widget :tag) "%{%t%}\n" "")
  596. (if (widget-member widget :doc) "%h" "")))
  597. ;; Write widget.
  598. (goto-char (point-max))
  599. (widget-default-create widget)
  600. (set-buffer-modified-p nil)
  601. (force-mode-line-update)
  602. (redisplay)))
  603. (defun xesam-get-hits (engine search hits)
  604. "Retrieve hits from ENGINE."
  605. (with-current-buffer (xesam-buffer-name (car engine) search)
  606. (setq xesam-objects
  607. (append xesam-objects
  608. (xesam-dbus-call-method
  609. :session (car engine) xesam-path-search
  610. xesam-interface-search "GetHits" search hits)))))
  611. (defun xesam-refresh-search-buffer (engine search)
  612. "Refreshes the buffer, presenting results of SEARCH."
  613. (with-current-buffer (xesam-buffer-name (car engine) search)
  614. ;; Work only if nobody else is here.
  615. (unless (or xesam-refreshing (>= xesam-current xesam-to))
  616. (setq xesam-refreshing t)
  617. (unwind-protect
  618. (let (widget)
  619. ;; Retrieve needed hits for visualization.
  620. (while (> (min xesam-to xesam-count) (length xesam-objects))
  621. (xesam-get-hits
  622. engine search
  623. (min xesam-hits-per-page
  624. (- (min xesam-to xesam-count) (length xesam-objects)))))
  625. ;; Add all result widgets.
  626. (while (< xesam-current (min xesam-to xesam-count))
  627. (setq xesam-current (1+ xesam-current))
  628. (xesam-refresh-entry engine search))
  629. ;; Add "NEXT" widget.
  630. (when (> xesam-count xesam-to)
  631. (goto-char (point-max))
  632. (widget-create
  633. 'link
  634. :notify
  635. (lambda (widget &rest ignore)
  636. (setq xesam-to (+ xesam-to xesam-hits-per-page))
  637. (widget-delete widget)
  638. (xesam-refresh-search-buffer xesam-engine xesam-search))
  639. "NEXT")
  640. (widget-beginning-of-line))
  641. ;; Prefetch next hits.
  642. (when (> (min (+ xesam-hits-per-page xesam-to) xesam-count)
  643. (length xesam-objects))
  644. (xesam-get-hits
  645. engine search
  646. (min xesam-hits-per-page
  647. (- (min (+ xesam-hits-per-page xesam-to) xesam-count)
  648. (length xesam-objects)))))
  649. ;; Add "DONE" widget.
  650. (when (= xesam-current xesam-count)
  651. (goto-char (point-max))
  652. (widget-create 'link :notify 'ignore "DONE")
  653. (widget-beginning-of-line)))
  654. ;; Return with save settings.
  655. (setq xesam-refreshing nil)))))
  656. ;;; Search functions.
  657. (defun xesam-signal-handler (&rest args)
  658. "Handles the different D-Bus signals of a Xesam search."
  659. (let* ((service (dbus-event-service-name last-input-event))
  660. (member (dbus-event-member-name last-input-event))
  661. (search (nth 0 args))
  662. (buffer (xesam-buffer-name service search)))
  663. (when (get-buffer buffer)
  664. (with-current-buffer buffer
  665. (cond
  666. ((string-equal member "HitsAdded")
  667. (setq xesam-count (+ xesam-count (nth 1 args)))
  668. ;; We use `run-at-time' in order to not block the event queue.
  669. (run-at-time
  670. 0 nil
  671. 'xesam-refresh-search-buffer
  672. (assoc service xesam-search-engines) search))
  673. ((string-equal member "SearchDone")
  674. (setq mode-line-process
  675. (propertize " Done" 'face 'xesam-mode-line))
  676. (force-mode-line-update)))))))
  677. (defun xesam-kill-buffer-function ()
  678. "Send the CloseSearch indication."
  679. (when (and (eq major-mode 'xesam-mode) (stringp xesam-search))
  680. (ignore-errors ;; The D-Bus service could have disappeared.
  681. (xesam-dbus-call-method
  682. :session (car xesam-engine) xesam-path-search
  683. xesam-interface-search "CloseSearch" xesam-search))))
  684. (defun xesam-new-search (engine type query)
  685. "Create a new search session.
  686. ENGINE identifies the search engine. TYPE is the query type, it
  687. can be either `fulltext-query', or `user-query'. QUERY is a
  688. string in the Xesam query language. A string, identifying the
  689. search, is returned."
  690. (let* ((service (car engine))
  691. (session (xesam-get-cached-property engine "session"))
  692. (xml-string
  693. (format
  694. (if (eq type 'user-query) xesam-user-query xesam-fulltext-query)
  695. (url-insert-entities-in-string query)))
  696. (search (xesam-dbus-call-method
  697. :session service xesam-path-search
  698. xesam-interface-search "NewSearch" session xml-string)))
  699. ;; Let us notify for relevant signals. We ignore "HitsRemoved",
  700. ;; "HitsModified" and "StateChanged"; there is nothing to do for
  701. ;; us.
  702. (dbus-register-signal
  703. :session service xesam-path-search
  704. xesam-interface-search "HitsAdded"
  705. 'xesam-signal-handler search)
  706. (dbus-register-signal
  707. :session service xesam-path-search
  708. xesam-interface-search "SearchDone"
  709. 'xesam-signal-handler search)
  710. ;; Create the search buffer.
  711. (with-current-buffer
  712. (generate-new-buffer (xesam-buffer-name service search))
  713. (switch-to-buffer-other-window (current-buffer))
  714. ;; Initialize buffer with `xesam-mode'. `xesam-vendor' must be
  715. ;; set before calling `xesam-mode', because we want to give the
  716. ;; hook functions a chance to identify their search engine.
  717. (setq xesam-vendor (xesam-get-cached-property engine "vendor.id"))
  718. (xesam-mode)
  719. (setq xesam-engine engine
  720. xesam-search search
  721. ;; `xesam-type', `xesam-query' and `xesam-xml-string'
  722. ;; are displayed in the header line.
  723. xesam-type (symbol-name type)
  724. xesam-query query
  725. xesam-xml-string xml-string
  726. xesam-objects nil
  727. ;; The buffer identification shall indicate the search
  728. ;; engine. The `help-echo' property is used for debug
  729. ;; information, when applicable.
  730. mode-line-buffer-identification
  731. (if (not xesam-debug)
  732. (list 12 (propertized-buffer-identification xesam-vendor))
  733. (propertize
  734. xesam-vendor
  735. 'help-echo
  736. (mapconcat
  737. (lambda (x)
  738. (format "%s: %s" x (xesam-get-cached-property engine x)))
  739. '("vendor.id" "vendor.version" "vendor.display" "vendor.xesam"
  740. "vendor.ontology.fields" "vendor.ontology.contents"
  741. "vendor.ontology.sources" "vendor.extensions"
  742. "vendor.ontologies" "vendor.maxhits")
  743. "\n"))))
  744. (add-hook 'kill-buffer-hook 'xesam-kill-buffer-function)
  745. (force-mode-line-update))
  746. ;; Start the search.
  747. (xesam-dbus-call-method
  748. :session (car engine) xesam-path-search
  749. xesam-interface-search "StartSearch" search)
  750. ;; Return search id.
  751. search))
  752. ;;;###autoload
  753. (defun xesam-search (engine query)
  754. "Perform an interactive search.
  755. ENGINE is the Xesam search engine to be applied, it must be one of the
  756. entries of `xesam-search-engines'. QUERY is the search string in the
  757. Xesam user query language. If the search engine does not support
  758. the Xesam user query language, a Xesam fulltext search is applied.
  759. The default search engine is the first entry in `xesam-search-engines'.
  760. Example:
  761. (xesam-search (car (xesam-search-engines)) \"emacs\")"
  762. (interactive
  763. (let* ((vendors (mapcar
  764. (lambda (x) (xesam-get-cached-property x "vendor.display"))
  765. (xesam-search-engines)))
  766. (vendor
  767. (if (> (length vendors) 1)
  768. (completing-read
  769. "Enter search engine: " vendors nil t
  770. (try-completion "" vendors) 'xesam-minibuffer-vendor-history)
  771. (car vendors))))
  772. (list
  773. ;; ENGINE.
  774. (when vendor
  775. (dolist (elt (xesam-search-engines) engine)
  776. (when (string-equal
  777. (xesam-get-cached-property elt "vendor.display") vendor)
  778. (setq engine elt))))
  779. ;; QUERY.
  780. (when vendor
  781. (read-from-minibuffer
  782. "Enter search string: " nil nil nil
  783. 'xesam-minibuffer-query-history)))))
  784. (if (null engine)
  785. (message "No search engine running")
  786. (if (zerop (length query))
  787. (message "No query applied")
  788. (xesam-new-search engine xesam-query-type query))))
  789. (provide 'xesam)
  790. ;;; TODO:
  791. ;; * Buffer highlighting needs better analysis of query string.
  792. ;; * Accept input while retrieving prefetched hits. `run-at-time'?
  793. ;; * With prefix, let's choose search engine.
  794. ;; * Minibuffer completion for user queries.
  795. ;; * `revert-buffer-function' implementation.
  796. ;;
  797. ;; * Mid term
  798. ;; - If available, use ontologies for field selection.
  799. ;; - Search engines for Emacs bugs database, wikipedia, google,
  800. ;; yahoo, ebay, ...
  801. ;; - Construct complex queries via widgets, like in mairix.el.
  802. ;;; xesam.el ends here