/
gowitt.go
401 lines (343 loc) · 10.2 KB
/
gowitt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package main
/*
TODO:
- Implement correct scrolling
- Display new tweets before replacing shortened urls, then expand urls as they arrive
- Stream tweets from the DB when scrolling up or down
- Asynchronous twitter timeline updating
- Do UI interaction (IMGUI-style maybe?)
- The image cache doesn't yet evict old images when new ones come in
- Add tweet time
- Proper error-handling everywhere
Known issues:
- The UI freezes when images are downloaded in the background, even though system is
architected so it's should never block. Which I guess means it's blocking somewhere
inside X11...
- The image cache doesn't yet evict old images when new ones come in
- Images are never removed from the cache directory
- Cairo surface is resized on every redraw. I think it should only do that upon
window resize
*/
import (
"encoding/json"
"errors"
"fmt"
"github.com/ChimeraCoder/anaconda"
"github.com/boltdb/bolt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"unsafe"
)
/*
#cgo pkg-config: pangocairo
#cgo LDFLAGS: -lX11
#include <pango/pango.h>
#include <pango/pangocairo.h>
#include <cairo/cairo.h>
#include <cairo/cairo-xlib.h>
int getXEventType(XEvent e){ return e.type; }
XKeyEvent eventAsKeyEvent(XEvent e){ return e.xkey; }
XButtonEvent eventAsButtonEvent(XEvent e){ return e.xbutton; }
long clientMessageType(XEvent e) { return e.xclient.data.l[0]; }
*/
import "C"
const UserImageSize = 48
const UIPadding = 5 // pixels of padding around stuff
const SmallPadding = 2 // pixels of smaller types of padding
type XWindow struct {
Display *C.Display
Window C.Window
// -- Pango
PangoContext *C.PangoContext
AttrList *C.PangoAttrList
FontDesc *C.PangoFontDescription
// Cairo
Cairo *C.cairo_t
Surface *C.cairo_surface_t
//
Scroll float64
UserImages *ImageCache
}
// The scrolling system works by keeping track of what tweet is the one on the
// middle of the screen, and scrolling around based on that. Once the center
// tweet is scrolled far enough to not be the center one anymore, the new
// center tweet is calculated, and a new scroll position is produced for it.
// Also, when tweets are streamed in or out, the centertweet value is readjusted
// so it keeps pointing to the same tweet
type ScrollPosition struct {
CenterTweet int
Scroll float32
}
func CreateXWindow(width, height int) (*XWindow, error) {
C.XInitThreads()
W := &XWindow{}
W.Display = C.XOpenDisplay(nil)
if W.Display == nil {
return &XWindow{}, errors.New("Can't open display")
}
W.Window = C.XCreateSimpleWindow(W.Display, C.XDefaultRootWindow(W.Display), 0, 0, C.uint(width), C.uint(height), 0, 0, 0xFF151515)
C.XSetWindowBackgroundPixmap(W.Display, W.Window, 0) // This avoids flickering on resize
C.XMapWindow(W.Display, W.Window)
C.XStoreName(W.Display, W.Window, C.CString("gowitt"))
C.XSelectInput(W.Display, W.Window, C.ExposureMask|C.KeyPressMask|C.ButtonPressMask)
C.XFlush(W.Display)
// Cairo
W.Surface = C.cairo_xlib_surface_create(W.Display, C.Drawable(W.Window), C.XDefaultVisual(W.Display, 0), C.int(width), C.int(height))
C.cairo_xlib_surface_set_size(W.Surface, C.int(width), C.int(height))
W.Cairo = C.cairo_create(W.Surface)
// Pango
InitLayoutsCache(W.Cairo)
W.PangoContext = C.pango_cairo_create_context(W.Cairo)
W.FontDesc = C.pango_font_description_from_string(C.CString("Sans 10"))
W.AttrList = C.pango_attr_list_new()
placeholderImage = C.cairo_image_surface_create_from_png(C.CString("test.png"))
W.UserImages = NewImageCache(func() {
var ev C.XEvent
exev := (*C.XExposeEvent)(unsafe.Pointer(&ev))
exev._type = C.Expose
exev.count = 0
exev.window = W.Window
exev.send_event = 1
exev.display = W.Display
C.XSendEvent(W.Display, W.Window, 0, C.ExposureMask, &ev)
C.XFlush(W.Display)
})
return W, nil
}
var placeholderImage *C.cairo_surface_t
func PixelsToPango(u float64) C.int {
return C.pango_units_from_double(C.double(u))
}
func PangoToPixels(u C.int) float64 {
return float64(C.pango_units_to_double(u))
}
func PangoRectToPixels(P *C.PangoRectangle) (x, y, w, h float64) {
return float64(C.pango_units_to_double(P.x)),
float64(C.pango_units_to_double(P.y)),
float64(C.pango_units_to_double(P.width)),
float64(C.pango_units_to_double(P.height))
}
func RedrawWindow(W *XWindow, tweetsList []*TweetInfo, mouseClick [2]int) {
var Attribs C.XWindowAttributes
C.XGetWindowAttributes(W.Display, W.Window, &Attribs)
// TODO -- Do this only when resizing?
C.cairo_xlib_surface_set_size(W.Surface, Attribs.width, Attribs.height)
C.cairo_set_source_rgb(W.Cairo, 0.1, 0.1, 0.1)
C.cairo_paint(W.Cairo)
var Rect C.PangoRectangle
yPos := 10.0 + W.Scroll
WindowWidth := Attribs.width
maxTweetWidth := PixelsToPango(float64(WindowWidth - 5*UIPadding - UserImageSize))
for i := 0; i < len(tweetsList); i++ {
t := tweetsList[i]
C.pango_layout_set_width(t.Layout, maxTweetWidth)
C.pango_layout_get_extents(t.Layout, nil, &Rect)
// Get tweet text size
_, ry, _, rh := PangoRectToPixels(&Rect)
// Position and add padding
ry += yPos
if rh < UserImageSize+2*UIPadding-UIPadding {
rh = UserImageSize + 2*UIPadding
} else {
rh += UIPadding
}
// Draw rectangle around tweet
C.cairo_set_source_rgb(W.Cairo, 0.2, 0.2, 0.2)
C.cairo_rectangle(W.Cairo, UIPadding, C.double(ry), C.double(WindowWidth-2*UIPadding), C.double(rh))
C.cairo_fill(W.Cairo)
if mouseClick[0] >= UIPadding && float64(mouseClick[1]) >= ry && float64(mouseClick[1]) <= ry+rh {
fmt.Println("Clicked tweet", t.Text)
}
// Draw user image
userImage := GetCachedImage(W.UserImages, t.UserImage)
if userImage == nil || C.cairo_surface_status(userImage) != C.CAIRO_STATUS_SUCCESS {
userImage = placeholderImage
}
C.cairo_set_source_surface(W.Cairo, userImage, 2*UIPadding, C.double(yPos+UIPadding))
C.cairo_paint(W.Cairo)
// Draw tweet text
C.cairo_move_to(W.Cairo, 63, C.double(yPos+SmallPadding))
C.cairo_set_source_rgb(W.Cairo, 0.95, 0.95, 0.95)
C.pango_cairo_show_layout(W.Cairo, t.Layout)
yPos += 5 + rh
}
}
func main() {
window, err := CreateXWindow(500, 500)
if err != nil {
panic(err)
}
defer C.XCloseDisplay(window.Display)
DB, err := initDB()
if err != nil {
panic(err)
}
//getTwitterData(DB)
tweetsList, err := regenerateViewData(window, DB, 20)
if err != nil {
panic(err)
}
wmDeleteMessage := C.XInternAtom(window.Display, C.CString("WM_DELETE_WINDOW"), 0)
C.XSetWMProtocols(window.Display, window.Window, &wmDeleteMessage, 1)
mouseClick := [2]int{-1, -1}
var event C.XEvent
for {
pendingRedraws := false
processedOneEvent := false
for !processedOneEvent || C.XPending(window.Display) != 0 {
C.XNextEvent(window.Display, &event)
processedOneEvent = true
switch C.getXEventType(event) {
case C.Expose:
pendingRedraws = true
case C.KeyPress:
ke := C.eventAsKeyEvent(event)
//fmt.Println("Key pressed", ke.keycode)
switch ke.keycode {
case 116: // down
window.Scroll -= 10
case 111: // up
window.Scroll += 10
}
pendingRedraws = true
case C.ButtonPress:
b := C.eventAsButtonEvent(event)
switch b.button {
case 4: // scroll up
window.Scroll += 10
case 5: // scroll down
window.Scroll -= 10
case 1:
// left mouse down
butEv := (*C.XButtonEvent)(unsafe.Pointer(&event))
mouseClick[0] = int(butEv.x)
mouseClick[1] = int(butEv.y)
}
pendingRedraws = true
case C.ClientMessage:
if C.clientMessageType(event) == C.long(wmDeleteMessage) {
return
}
}
}
if pendingRedraws {
RedrawWindow(window, tweetsList, mouseClick)
mouseClick[0] = -1
mouseClick[1] = -1
}
}
}
func regenerateViewData(W *XWindow, DB *bolt.DB, MaxTweets int) ([]*TweetInfo, error) {
tweets, err := getLastNTweets(DB, MaxTweets)
if err != nil {
return []*TweetInfo{}, err
}
var Result []*TweetInfo
for i := range tweets {
Result = append(Result, GenerateTweetInfo(W, &tweets[i]))
}
return Result, nil
}
func getTwitterData(DB *bolt.DB) {
anaconda.SetConsumerKey("KmxA5PMS1WaVdSnJrYtq5XANb")
anaconda.SetConsumerSecret("yt7ydv2qFt7BpyHrMK3UzIj7HXGGv7ezcVTnELxhgh2WMGj9IA")
api := anaconda.NewTwitterApi(
"268263175-deYL6a9YyDMy8YRDQI0p9NDBoKuZScRKG24Dpqkj",
"PrFnSYOzsZjPYc5zhN9qeviyyHH0x1sKkiOYSSyPdWrnS")
tweets, err := api.GetHomeTimeline(url.Values{
"count": {"10"},
})
if err != nil {
// TODO -- Handle timeouts here
panic(err)
}
Tx, err := DB.Begin(true)
if err != nil {
// TODO -- Handle this gracely
panic(err)
}
Bucket := Tx.Bucket([]byte("tweets"))
for _, t := range tweets {
tweetText := t.Text
if t.RetweetedStatus != nil {
tweetText = t.RetweetedStatus.Text
}
tweetText = replaceURLS(tweetText, func(s string) string {
fmt.Println("Replacing ", s)
for retries := 0; retries < 3; retries++ {
newS, err := getRedirectedURL(s)
if err != nil {
time.Sleep(time.Duration(1+retries) * time.Second)
continue
}
return newS
}
return s
})
if t.RetweetedStatus != nil {
t.RetweetedStatus.Text = tweetText
} else {
t.Text = tweetText
}
data, err := json.Marshal(t)
if err != nil {
Tx.Rollback()
DB.Sync()
panic(err)
}
key := []byte(strconv.FormatInt(t.Id, 16))
if err = Bucket.Put(key, data); err != nil {
Tx.Rollback()
DB.Sync()
panic(err)
}
}
Tx.Commit()
}
// Auxiliary function to get original URLs from URL shorteners
func getRedirectedURL(URL string) (string, error) {
var Result string
c := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
Result = req.URL.String()
return errors.New("")
}}
_, err := c.Get(URL)
if Result != "" {
return Result, nil
}
return Result, err
}
// Replace all urls found in input string with the output of the supplied function
func replaceURLS(s string, txFunc func(string) string) string {
var output string
for {
// Find instances of http(s)://
p := strings.Index(s, "http://")
if p == -1 {
p = strings.Index(s, "https://")
}
// Add non-url text to output string
if p == -1 {
output += s
break
}
if p > 0 {
output += s[:p]
s = s[p:]
}
// Find where url ends (space or string end)
end := strings.Index(s, " ")
if end == -1 {
end = len(s)
}
// transform url
newUrl := txFunc(s[:end])
output += newUrl
s = s[end:]
}
return output
}