repo
string | commit
string | message
string | diff
string |
---|---|---|---|
jeffkreeftmeijer/dotfiles
|
083000075e27644840741a8df31f39684d164e62
|
Add vim-rhubarb
|
diff --git a/.gitmodules b/.gitmodules
index 8adb4e9..90d03f4 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -1,30 +1,33 @@
[submodule "nvim/pack/plugins/start/vim-tmux-navigator"]
path = nvim/pack/plugins/start/vim-tmux-navigator
url = [email protected]:christoomey/vim-tmux-navigator.git
[submodule "nvim/pack/plugins/start/neovim-sensible"]
path = nvim/pack/plugins/start/neovim-sensible
url = [email protected]:jeffkreeftmeijer/neovim-sensible.git
[submodule "nvim/pack/plugins/start/vim-dim"]
path = nvim/pack/plugins/start/vim-dim
url = [email protected]:jeffkreeftmeijer/vim-dim.git
[submodule "nvim/pack/plugins/start/vim-numbertoggle"]
path = nvim/pack/plugins/start/vim-numbertoggle
url = [email protected]:jeffkreeftmeijer/vim-numbertoggle.git
[submodule "nvim/pack/plugins/start/fzf.vim"]
path = nvim/pack/plugins/start/fzf.vim
url = [email protected]:junegunn/fzf.vim.git
[submodule "nvim/pack/plugins/start/goyo.vim"]
path = nvim/pack/plugins/start/goyo.vim
url = [email protected]:junegunn/goyo.vim.git
[submodule "nvim/pack/plugins/start/vim-polyglot"]
path = nvim/pack/plugins/start/vim-polyglot
url = [email protected]:sheerun/vim-polyglot.git
[submodule "nvim/pack/plugins/start/vim-commentary"]
path = nvim/pack/plugins/start/vim-commentary
url = [email protected]:tpope/vim-commentary.git
[submodule "nvim/pack/plugins/start/vim-fugitive"]
path = nvim/pack/plugins/start/vim-fugitive
url = [email protected]:tpope/vim-fugitive.git
[submodule "nvim/pack/plugins/start/ale"]
path = nvim/pack/plugins/start/ale
url = [email protected]:w0rp/ale.git
+[submodule "nvim/pack/plugins/start/vim-rhubarb"]
+ path = nvim/pack/plugins/start/vim-rhubarb
+ url = [email protected]:tpope/vim-rhubarb.git
diff --git a/nvim/pack/plugins/start/vim-rhubarb b/nvim/pack/plugins/start/vim-rhubarb
new file mode 160000
index 0000000..6caad2b
--- /dev/null
+++ b/nvim/pack/plugins/start/vim-rhubarb
@@ -0,0 +1 @@
+Subproject commit 6caad2b61afcc1b7c476b0ae3dea9ee5f2b1d14a
|
jeffkreeftmeijer/dotfiles
|
5e73992130fbe01eb57431af59809172b77e14a4
|
Move mouse mode to neovim-sensible
|
diff --git a/nvim/init.vim b/nvim/init.vim
index aece694..f9ca864 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,14 +1,11 @@
colors dim
set bg=dark
-" Enable mouse/trackpad scrolling
-set mouse=a
-
" fzf.vim
set rtp+=/usr/local/opt/fzf
nnoremap <silent> ,t :Files<CR>
nnoremap <silent> ,b :Buffers<CR>
nnoremap <silent> ,a :Ag<CR>
" ale
let g:ale_lint_on_text_changed = 'never'
diff --git a/nvim/pack/plugins/start/neovim-sensible b/nvim/pack/plugins/start/neovim-sensible
index 41dd70b..e7ab754 160000
--- a/nvim/pack/plugins/start/neovim-sensible
+++ b/nvim/pack/plugins/start/neovim-sensible
@@ -1 +1 @@
-Subproject commit 41dd70be9a77598082f95d8541fcb5a8eb50d129
+Subproject commit e7ab7544f15e59de2d9a1b42f58e590938e496e7
|
jeffkreeftmeijer/dotfiles
|
8c5f89030e22cbdeb6ae85f649cdf9612ae4a353
|
set bg=dark in init.vim
|
diff --git a/nvim/init.vim b/nvim/init.vim
index 482f7bf..aece694 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,13 +1,14 @@
colors dim
+set bg=dark
" Enable mouse/trackpad scrolling
set mouse=a
" fzf.vim
set rtp+=/usr/local/opt/fzf
nnoremap <silent> ,t :Files<CR>
nnoremap <silent> ,b :Buffers<CR>
nnoremap <silent> ,a :Ag<CR>
" ale
let g:ale_lint_on_text_changed = 'never'
|
jeffkreeftmeijer/dotfiles
|
888f413c8c0754972ac53fe0d304317a533fab9b
|
Use fzf from brew
|
diff --git a/nvim/init.vim b/nvim/init.vim
index 6d617d9..482f7bf 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,12 +1,13 @@
colors dim
" Enable mouse/trackpad scrolling
set mouse=a
" fzf.vim
+set rtp+=/usr/local/opt/fzf
nnoremap <silent> ,t :Files<CR>
nnoremap <silent> ,b :Buffers<CR>
nnoremap <silent> ,a :Ag<CR>
" ale
let g:ale_lint_on_text_changed = 'never'
|
jeffkreeftmeijer/dotfiles
|
487c83cc4501462d4e3a2df01965ee08c1288d41
|
Remove Plug
|
diff --git a/nvim/autoload/plug.vim b/nvim/autoload/plug.vim
deleted file mode 100644
index b0f5bc2..0000000
--- a/nvim/autoload/plug.vim
+++ /dev/null
@@ -1,2414 +0,0 @@
-" vim-plug: Vim plugin manager
-" ============================
-"
-" Download plug.vim and put it in ~/.vim/autoload
-"
-" curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
-" https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
-"
-" Edit your .vimrc
-"
-" call plug#begin('~/.vim/plugged')
-"
-" " Make sure you use single quotes
-"
-" " Shorthand notation; fetches https://github.com/junegunn/vim-easy-align
-" Plug 'junegunn/vim-easy-align'
-"
-" " Any valid git URL is allowed
-" Plug 'https://github.com/junegunn/vim-github-dashboard.git'
-"
-" " Group dependencies, vim-snippets depends on ultisnips
-" Plug 'SirVer/ultisnips' | Plug 'honza/vim-snippets'
-"
-" " On-demand loading
-" Plug 'scrooloose/nerdtree', { 'on': 'NERDTreeToggle' }
-" Plug 'tpope/vim-fireplace', { 'for': 'clojure' }
-"
-" " Using a non-master branch
-" Plug 'rdnetto/YCM-Generator', { 'branch': 'stable' }
-"
-" " Using a tagged release; wildcard allowed (requires git 1.9.2 or above)
-" Plug 'fatih/vim-go', { 'tag': '*' }
-"
-" " Plugin options
-" Plug 'nsf/gocode', { 'tag': 'v.20150303', 'rtp': 'vim' }
-"
-" " Plugin outside ~/.vim/plugged with post-update hook
-" Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
-"
-" " Unmanaged plugin (manually installed and updated)
-" Plug '~/my-prototype-plugin'
-"
-" " Add plugins to &runtimepath
-" call plug#end()
-"
-" Then reload .vimrc and :PlugInstall to install plugins.
-"
-" Plug options:
-"
-"| Option | Description |
-"| ----------------------- | ------------------------------------------------ |
-"| `branch`/`tag`/`commit` | Branch/tag/commit of the repository to use |
-"| `rtp` | Subdirectory that contains Vim plugin |
-"| `dir` | Custom directory for the plugin |
-"| `as` | Use different name for the plugin |
-"| `do` | Post-update hook (string or funcref) |
-"| `on` | On-demand loading: Commands or `<Plug>`-mappings |
-"| `for` | On-demand loading: File types |
-"| `frozen` | Do not update unless explicitly specified |
-"
-" More information: https://github.com/junegunn/vim-plug
-"
-"
-" Copyright (c) 2016 Junegunn Choi
-"
-" MIT License
-"
-" Permission is hereby granted, free of charge, to any person obtaining
-" a copy of this software and associated documentation files (the
-" "Software"), to deal in the Software without restriction, including
-" without limitation the rights to use, copy, modify, merge, publish,
-" distribute, sublicense, and/or sell copies of the Software, and to
-" permit persons to whom the Software is furnished to do so, subject to
-" the following conditions:
-"
-" The above copyright notice and this permission notice shall be
-" included in all copies or substantial portions of the Software.
-"
-" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-" NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-" LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-" OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-" WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-if exists('g:loaded_plug')
- finish
-endif
-let g:loaded_plug = 1
-
-let s:cpo_save = &cpo
-set cpo&vim
-
-let s:plug_src = 'https://github.com/junegunn/vim-plug.git'
-let s:plug_tab = get(s:, 'plug_tab', -1)
-let s:plug_buf = get(s:, 'plug_buf', -1)
-let s:mac_gui = has('gui_macvim') && has('gui_running')
-let s:is_win = has('win32') || has('win64')
-let s:nvim = has('nvim') && exists('*jobwait') && !s:is_win
-let s:vim8 = has('patch-8.0.0039') && exists('*job_start')
-let s:me = resolve(expand('<sfile>:p'))
-let s:base_spec = { 'branch': 'master', 'frozen': 0 }
-let s:TYPE = {
-\ 'string': type(''),
-\ 'list': type([]),
-\ 'dict': type({}),
-\ 'funcref': type(function('call'))
-\ }
-let s:loaded = get(s:, 'loaded', {})
-let s:triggers = get(s:, 'triggers', {})
-
-function! plug#begin(...)
- if a:0 > 0
- let s:plug_home_org = a:1
- let home = s:path(fnamemodify(expand(a:1), ':p'))
- elseif exists('g:plug_home')
- let home = s:path(g:plug_home)
- elseif !empty(&rtp)
- let home = s:path(split(&rtp, ',')[0]) . '/plugged'
- else
- return s:err('Unable to determine plug home. Try calling plug#begin() with a path argument.')
- endif
-
- let g:plug_home = home
- let g:plugs = {}
- let g:plugs_order = []
- let s:triggers = {}
-
- call s:define_commands()
- return 1
-endfunction
-
-function! s:define_commands()
- command! -nargs=+ -bar Plug call plug#(<args>)
- if !executable('git')
- return s:err('`git` executable not found. Most commands will not be available. To suppress this message, prepend `silent!` to `call plug#begin(...)`.')
- endif
- command! -nargs=* -bar -bang -complete=customlist,s:names PlugInstall call s:install(<bang>0, [<f-args>])
- command! -nargs=* -bar -bang -complete=customlist,s:names PlugUpdate call s:update(<bang>0, [<f-args>])
- command! -nargs=0 -bar -bang PlugClean call s:clean(<bang>0)
- command! -nargs=0 -bar PlugUpgrade if s:upgrade() | execute 'source' s:esc(s:me) | endif
- command! -nargs=0 -bar PlugStatus call s:status()
- command! -nargs=0 -bar PlugDiff call s:diff()
- command! -nargs=? -bar -bang -complete=file PlugSnapshot call s:snapshot(<bang>0, <f-args>)
-endfunction
-
-function! s:to_a(v)
- return type(a:v) == s:TYPE.list ? a:v : [a:v]
-endfunction
-
-function! s:to_s(v)
- return type(a:v) == s:TYPE.string ? a:v : join(a:v, "\n") . "\n"
-endfunction
-
-function! s:glob(from, pattern)
- return s:lines(globpath(a:from, a:pattern))
-endfunction
-
-function! s:source(from, ...)
- let found = 0
- for pattern in a:000
- for vim in s:glob(a:from, pattern)
- execute 'source' s:esc(vim)
- let found = 1
- endfor
- endfor
- return found
-endfunction
-
-function! s:assoc(dict, key, val)
- let a:dict[a:key] = add(get(a:dict, a:key, []), a:val)
-endfunction
-
-function! s:ask(message, ...)
- call inputsave()
- echohl WarningMsg
- let answer = input(a:message.(a:0 ? ' (y/N/a) ' : ' (y/N) '))
- echohl None
- call inputrestore()
- echo "\r"
- return (a:0 && answer =~? '^a') ? 2 : (answer =~? '^y') ? 1 : 0
-endfunction
-
-function! s:ask_no_interrupt(...)
- try
- return call('s:ask', a:000)
- catch
- return 0
- endtry
-endfunction
-
-function! plug#end()
- if !exists('g:plugs')
- return s:err('Call plug#begin() first')
- endif
-
- if exists('#PlugLOD')
- augroup PlugLOD
- autocmd!
- augroup END
- augroup! PlugLOD
- endif
- let lod = { 'ft': {}, 'map': {}, 'cmd': {} }
-
- if exists('g:did_load_filetypes')
- filetype off
- endif
- for name in g:plugs_order
- if !has_key(g:plugs, name)
- continue
- endif
- let plug = g:plugs[name]
- if get(s:loaded, name, 0) || !has_key(plug, 'on') && !has_key(plug, 'for')
- let s:loaded[name] = 1
- continue
- endif
-
- if has_key(plug, 'on')
- let s:triggers[name] = { 'map': [], 'cmd': [] }
- for cmd in s:to_a(plug.on)
- if cmd =~? '^<Plug>.\+'
- if empty(mapcheck(cmd)) && empty(mapcheck(cmd, 'i'))
- call s:assoc(lod.map, cmd, name)
- endif
- call add(s:triggers[name].map, cmd)
- elseif cmd =~# '^[A-Z]'
- if exists(':'.cmd) != 2
- call s:assoc(lod.cmd, cmd, name)
- endif
- call add(s:triggers[name].cmd, cmd)
- else
- call s:err('Invalid `on` option: '.cmd.
- \ '. Should start with an uppercase letter or `<Plug>`.')
- endif
- endfor
- endif
-
- if has_key(plug, 'for')
- let types = s:to_a(plug.for)
- if !empty(types)
- augroup filetypedetect
- call s:source(s:rtp(plug), 'ftdetect/**/*.vim', 'after/ftdetect/**/*.vim')
- augroup END
- endif
- for type in types
- call s:assoc(lod.ft, type, name)
- endfor
- endif
- endfor
-
- for [cmd, names] in items(lod.cmd)
- execute printf(
- \ 'command! -nargs=* -range -bang -complete=file %s call s:lod_cmd(%s, "<bang>", <line1>, <line2>, <q-args>, %s)',
- \ cmd, string(cmd), string(names))
- endfor
-
- for [map, names] in items(lod.map)
- for [mode, map_prefix, key_prefix] in
- \ [['i', '<C-O>', ''], ['n', '', ''], ['v', '', 'gv'], ['o', '', '']]
- execute printf(
- \ '%snoremap <silent> %s %s:<C-U>call <SID>lod_map(%s, %s, %s, "%s")<CR>',
- \ mode, map, map_prefix, string(map), string(names), mode != 'i', key_prefix)
- endfor
- endfor
-
- for [ft, names] in items(lod.ft)
- augroup PlugLOD
- execute printf('autocmd FileType %s call <SID>lod_ft(%s, %s)',
- \ ft, string(ft), string(names))
- augroup END
- endfor
-
- call s:reorg_rtp()
- filetype plugin indent on
- if has('vim_starting')
- if has('syntax') && !exists('g:syntax_on')
- syntax enable
- end
- else
- call s:reload_plugins()
- endif
-endfunction
-
-function! s:loaded_names()
- return filter(copy(g:plugs_order), 'get(s:loaded, v:val, 0)')
-endfunction
-
-function! s:load_plugin(spec)
- call s:source(s:rtp(a:spec), 'plugin/**/*.vim', 'after/plugin/**/*.vim')
-endfunction
-
-function! s:reload_plugins()
- for name in s:loaded_names()
- call s:load_plugin(g:plugs[name])
- endfor
-endfunction
-
-function! s:trim(str)
- return substitute(a:str, '[\/]\+$', '', '')
-endfunction
-
-function! s:version_requirement(val, min)
- for idx in range(0, len(a:min) - 1)
- let v = get(a:val, idx, 0)
- if v < a:min[idx] | return 0
- elseif v > a:min[idx] | return 1
- endif
- endfor
- return 1
-endfunction
-
-function! s:git_version_requirement(...)
- if !exists('s:git_version')
- let s:git_version = map(split(split(s:system('git --version'))[2], '\.'), 'str2nr(v:val)')
- endif
- return s:version_requirement(s:git_version, a:000)
-endfunction
-
-function! s:progress_opt(base)
- return a:base && !s:is_win &&
- \ s:git_version_requirement(1, 7, 1) ? '--progress' : ''
-endfunction
-
-if s:is_win
- function! s:rtp(spec)
- return s:path(a:spec.dir . get(a:spec, 'rtp', ''))
- endfunction
-
- function! s:path(path)
- return s:trim(substitute(a:path, '/', '\', 'g'))
- endfunction
-
- function! s:dirpath(path)
- return s:path(a:path) . '\'
- endfunction
-
- function! s:is_local_plug(repo)
- return a:repo =~? '^[a-z]:\|^[%~]'
- endfunction
-else
- function! s:rtp(spec)
- return s:dirpath(a:spec.dir . get(a:spec, 'rtp', ''))
- endfunction
-
- function! s:path(path)
- return s:trim(a:path)
- endfunction
-
- function! s:dirpath(path)
- return substitute(a:path, '[/\\]*$', '/', '')
- endfunction
-
- function! s:is_local_plug(repo)
- return a:repo[0] =~ '[/$~]'
- endfunction
-endif
-
-function! s:err(msg)
- echohl ErrorMsg
- echom '[vim-plug] '.a:msg
- echohl None
-endfunction
-
-function! s:warn(cmd, msg)
- echohl WarningMsg
- execute a:cmd 'a:msg'
- echohl None
-endfunction
-
-function! s:esc(path)
- return escape(a:path, ' ')
-endfunction
-
-function! s:escrtp(path)
- return escape(a:path, ' ,')
-endfunction
-
-function! s:remove_rtp()
- for name in s:loaded_names()
- let rtp = s:rtp(g:plugs[name])
- execute 'set rtp-='.s:escrtp(rtp)
- let after = globpath(rtp, 'after')
- if isdirectory(after)
- execute 'set rtp-='.s:escrtp(after)
- endif
- endfor
-endfunction
-
-function! s:reorg_rtp()
- if !empty(s:first_rtp)
- execute 'set rtp-='.s:first_rtp
- execute 'set rtp-='.s:last_rtp
- endif
-
- " &rtp is modified from outside
- if exists('s:prtp') && s:prtp !=# &rtp
- call s:remove_rtp()
- unlet! s:middle
- endif
-
- let s:middle = get(s:, 'middle', &rtp)
- let rtps = map(s:loaded_names(), 's:rtp(g:plugs[v:val])')
- let afters = filter(map(copy(rtps), 'globpath(v:val, "after")'), '!empty(v:val)')
- let rtp = join(map(rtps, 'escape(v:val, ",")'), ',')
- \ . ','.s:middle.','
- \ . join(map(afters, 'escape(v:val, ",")'), ',')
- let &rtp = substitute(substitute(rtp, ',,*', ',', 'g'), '^,\|,$', '', 'g')
- let s:prtp = &rtp
-
- if !empty(s:first_rtp)
- execute 'set rtp^='.s:first_rtp
- execute 'set rtp+='.s:last_rtp
- endif
-endfunction
-
-function! s:doautocmd(...)
- if exists('#'.join(a:000, '#'))
- execute 'doautocmd' ((v:version > 703 || has('patch442')) ? '<nomodeline>' : '') join(a:000)
- endif
-endfunction
-
-function! s:dobufread(names)
- for name in a:names
- let path = s:rtp(g:plugs[name]).'/**'
- for dir in ['ftdetect', 'ftplugin']
- if len(finddir(dir, path))
- return s:doautocmd('BufRead')
- endif
- endfor
- endfor
-endfunction
-
-function! plug#load(...)
- if a:0 == 0
- return s:err('Argument missing: plugin name(s) required')
- endif
- if !exists('g:plugs')
- return s:err('plug#begin was not called')
- endif
- let unknowns = filter(copy(a:000), '!has_key(g:plugs, v:val)')
- if !empty(unknowns)
- let s = len(unknowns) > 1 ? 's' : ''
- return s:err(printf('Unknown plugin%s: %s', s, join(unknowns, ', ')))
- end
- for name in a:000
- call s:lod([name], ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
- endfor
- call s:dobufread(a:000)
- return 1
-endfunction
-
-function! s:remove_triggers(name)
- if !has_key(s:triggers, a:name)
- return
- endif
- for cmd in s:triggers[a:name].cmd
- execute 'silent! delc' cmd
- endfor
- for map in s:triggers[a:name].map
- execute 'silent! unmap' map
- execute 'silent! iunmap' map
- endfor
- call remove(s:triggers, a:name)
-endfunction
-
-function! s:lod(names, types, ...)
- for name in a:names
- call s:remove_triggers(name)
- let s:loaded[name] = 1
- endfor
- call s:reorg_rtp()
-
- for name in a:names
- let rtp = s:rtp(g:plugs[name])
- for dir in a:types
- call s:source(rtp, dir.'/**/*.vim')
- endfor
- if a:0
- if !s:source(rtp, a:1) && !empty(s:glob(rtp, a:2))
- execute 'runtime' a:1
- endif
- call s:source(rtp, a:2)
- endif
- call s:doautocmd('User', name)
- endfor
-endfunction
-
-function! s:lod_ft(pat, names)
- let syn = 'syntax/'.a:pat.'.vim'
- call s:lod(a:names, ['plugin', 'after/plugin'], syn, 'after/'.syn)
- execute 'autocmd! PlugLOD FileType' a:pat
- call s:doautocmd('filetypeplugin', 'FileType')
- call s:doautocmd('filetypeindent', 'FileType')
-endfunction
-
-function! s:lod_cmd(cmd, bang, l1, l2, args, names)
- call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
- call s:dobufread(a:names)
- execute printf('%s%s%s %s', (a:l1 == a:l2 ? '' : (a:l1.','.a:l2)), a:cmd, a:bang, a:args)
-endfunction
-
-function! s:lod_map(map, names, with_prefix, prefix)
- call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
- call s:dobufread(a:names)
- let extra = ''
- while 1
- let c = getchar(0)
- if c == 0
- break
- endif
- let extra .= nr2char(c)
- endwhile
-
- if a:with_prefix
- let prefix = v:count ? v:count : ''
- let prefix .= '"'.v:register.a:prefix
- if mode(1) == 'no'
- if v:operator == 'c'
- let prefix = "\<esc>" . prefix
- endif
- let prefix .= v:operator
- endif
- call feedkeys(prefix, 'n')
- endif
- call feedkeys(substitute(a:map, '^<Plug>', "\<Plug>", '') . extra)
-endfunction
-
-function! plug#(repo, ...)
- if a:0 > 1
- return s:err('Invalid number of arguments (1..2)')
- endif
-
- try
- let repo = s:trim(a:repo)
- let opts = a:0 == 1 ? s:parse_options(a:1) : s:base_spec
- let name = get(opts, 'as', fnamemodify(repo, ':t:s?\.git$??'))
- let spec = extend(s:infer_properties(name, repo), opts)
- if !has_key(g:plugs, name)
- call add(g:plugs_order, name)
- endif
- let g:plugs[name] = spec
- let s:loaded[name] = get(s:loaded, name, 0)
- catch
- return s:err(v:exception)
- endtry
-endfunction
-
-function! s:parse_options(arg)
- let opts = copy(s:base_spec)
- let type = type(a:arg)
- if type == s:TYPE.string
- let opts.tag = a:arg
- elseif type == s:TYPE.dict
- call extend(opts, a:arg)
- if has_key(opts, 'dir')
- let opts.dir = s:dirpath(expand(opts.dir))
- endif
- else
- throw 'Invalid argument type (expected: string or dictionary)'
- endif
- return opts
-endfunction
-
-function! s:infer_properties(name, repo)
- let repo = a:repo
- if s:is_local_plug(repo)
- return { 'dir': s:dirpath(expand(repo)) }
- else
- if repo =~ ':'
- let uri = repo
- else
- if repo !~ '/'
- let repo = 'vim-scripts/'. repo
- endif
- let fmt = get(g:, 'plug_url_format', 'https://git::@github.com/%s.git')
- let uri = printf(fmt, repo)
- endif
- return { 'dir': s:dirpath(g:plug_home.'/'.a:name), 'uri': uri }
- endif
-endfunction
-
-function! s:install(force, names)
- call s:update_impl(0, a:force, a:names)
-endfunction
-
-function! s:update(force, names)
- call s:update_impl(1, a:force, a:names)
-endfunction
-
-function! plug#helptags()
- if !exists('g:plugs')
- return s:err('plug#begin was not called')
- endif
- for spec in values(g:plugs)
- let docd = join([spec.dir, 'doc'], '/')
- if isdirectory(docd)
- silent! execute 'helptags' s:esc(docd)
- endif
- endfor
- return 1
-endfunction
-
-function! s:syntax()
- syntax clear
- syntax region plug1 start=/\%1l/ end=/\%2l/ contains=plugNumber
- syntax region plug2 start=/\%2l/ end=/\%3l/ contains=plugBracket,plugX
- syn match plugNumber /[0-9]\+[0-9.]*/ contained
- syn match plugBracket /[[\]]/ contained
- syn match plugX /x/ contained
- syn match plugDash /^-/
- syn match plugPlus /^+/
- syn match plugStar /^*/
- syn match plugMessage /\(^- \)\@<=.*/
- syn match plugName /\(^- \)\@<=[^ ]*:/
- syn match plugSha /\%(: \)\@<=[0-9a-f]\{4,}$/
- syn match plugTag /(tag: [^)]\+)/
- syn match plugInstall /\(^+ \)\@<=[^:]*/
- syn match plugUpdate /\(^* \)\@<=[^:]*/
- syn match plugCommit /^ \X*[0-9a-f]\{7} .*/ contains=plugRelDate,plugEdge,plugTag
- syn match plugEdge /^ \X\+$/
- syn match plugEdge /^ \X*/ contained nextgroup=plugSha
- syn match plugSha /[0-9a-f]\{7}/ contained
- syn match plugRelDate /([^)]*)$/ contained
- syn match plugNotLoaded /(not loaded)$/
- syn match plugError /^x.*/
- syn region plugDeleted start=/^\~ .*/ end=/^\ze\S/
- syn match plugH2 /^.*:\n-\+$/
- syn keyword Function PlugInstall PlugStatus PlugUpdate PlugClean
- hi def link plug1 Title
- hi def link plug2 Repeat
- hi def link plugH2 Type
- hi def link plugX Exception
- hi def link plugBracket Structure
- hi def link plugNumber Number
-
- hi def link plugDash Special
- hi def link plugPlus Constant
- hi def link plugStar Boolean
-
- hi def link plugMessage Function
- hi def link plugName Label
- hi def link plugInstall Function
- hi def link plugUpdate Type
-
- hi def link plugError Error
- hi def link plugDeleted Ignore
- hi def link plugRelDate Comment
- hi def link plugEdge PreProc
- hi def link plugSha Identifier
- hi def link plugTag Constant
-
- hi def link plugNotLoaded Comment
-endfunction
-
-function! s:lpad(str, len)
- return a:str . repeat(' ', a:len - len(a:str))
-endfunction
-
-function! s:lines(msg)
- return split(a:msg, "[\r\n]")
-endfunction
-
-function! s:lastline(msg)
- return get(s:lines(a:msg), -1, '')
-endfunction
-
-function! s:new_window()
- execute get(g:, 'plug_window', 'vertical topleft new')
-endfunction
-
-function! s:plug_window_exists()
- let buflist = tabpagebuflist(s:plug_tab)
- return !empty(buflist) && index(buflist, s:plug_buf) >= 0
-endfunction
-
-function! s:switch_in()
- if !s:plug_window_exists()
- return 0
- endif
-
- if winbufnr(0) != s:plug_buf
- let s:pos = [tabpagenr(), winnr(), winsaveview()]
- execute 'normal!' s:plug_tab.'gt'
- let winnr = bufwinnr(s:plug_buf)
- execute winnr.'wincmd w'
- call add(s:pos, winsaveview())
- else
- let s:pos = [winsaveview()]
- endif
-
- setlocal modifiable
- return 1
-endfunction
-
-function! s:switch_out(...)
- call winrestview(s:pos[-1])
- setlocal nomodifiable
- if a:0 > 0
- execute a:1
- endif
-
- if len(s:pos) > 1
- execute 'normal!' s:pos[0].'gt'
- execute s:pos[1] 'wincmd w'
- call winrestview(s:pos[2])
- endif
-endfunction
-
-function! s:finish_bindings()
- nnoremap <silent> <buffer> R :call <SID>retry()<cr>
- nnoremap <silent> <buffer> D :PlugDiff<cr>
- nnoremap <silent> <buffer> S :PlugStatus<cr>
- nnoremap <silent> <buffer> U :call <SID>status_update()<cr>
- xnoremap <silent> <buffer> U :call <SID>status_update()<cr>
- nnoremap <silent> <buffer> ]] :silent! call <SID>section('')<cr>
- nnoremap <silent> <buffer> [[ :silent! call <SID>section('b')<cr>
-endfunction
-
-function! s:prepare(...)
- if empty(getcwd())
- throw 'Invalid current working directory. Cannot proceed.'
- endif
-
- for evar in ['$GIT_DIR', '$GIT_WORK_TREE']
- if exists(evar)
- throw evar.' detected. Cannot proceed.'
- endif
- endfor
-
- call s:job_abort()
- if s:switch_in()
- if b:plug_preview == 1
- pc
- endif
- enew
- else
- call s:new_window()
- endif
-
- nnoremap <silent> <buffer> q :if b:plug_preview==1<bar>pc<bar>endif<bar>bd<cr>
- if a:0 == 0
- call s:finish_bindings()
- endif
- let b:plug_preview = -1
- let s:plug_tab = tabpagenr()
- let s:plug_buf = winbufnr(0)
- call s:assign_name()
-
- for k in ['<cr>', 'L', 'o', 'X', 'd', 'dd']
- execute 'silent! unmap <buffer>' k
- endfor
- setlocal buftype=nofile bufhidden=wipe nobuflisted nolist noswapfile nowrap cursorline modifiable
- setf vim-plug
- if exists('g:syntax_on')
- call s:syntax()
- endif
-endfunction
-
-function! s:assign_name()
- " Assign buffer name
- let prefix = '[Plugins]'
- let name = prefix
- let idx = 2
- while bufexists(name)
- let name = printf('%s (%s)', prefix, idx)
- let idx = idx + 1
- endwhile
- silent! execute 'f' fnameescape(name)
-endfunction
-
-function! s:chsh(swap)
- let prev = [&shell, &shellredir]
- if !s:is_win && a:swap
- set shell=sh shellredir=>%s\ 2>&1
- endif
- return prev
-endfunction
-
-function! s:bang(cmd, ...)
- try
- let [sh, shrd] = s:chsh(a:0)
- " FIXME: Escaping is incomplete. We could use shellescape with eval,
- " but it won't work on Windows.
- let cmd = a:0 ? s:with_cd(a:cmd, a:1) : a:cmd
- let g:_plug_bang = '!'.escape(cmd, '#!%')
- execute "normal! :execute g:_plug_bang\<cr>\<cr>"
- finally
- unlet g:_plug_bang
- let [&shell, &shellredir] = [sh, shrd]
- endtry
- return v:shell_error ? 'Exit status: ' . v:shell_error : ''
-endfunction
-
-function! s:regress_bar()
- let bar = substitute(getline(2)[1:-2], '.*\zs=', 'x', '')
- call s:progress_bar(2, bar, len(bar))
-endfunction
-
-function! s:is_updated(dir)
- return !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"', a:dir))
-endfunction
-
-function! s:do(pull, force, todo)
- for [name, spec] in items(a:todo)
- if !isdirectory(spec.dir)
- continue
- endif
- let installed = has_key(s:update.new, name)
- let updated = installed ? 0 :
- \ (a:pull && index(s:update.errors, name) < 0 && s:is_updated(spec.dir))
- if a:force || installed || updated
- execute 'cd' s:esc(spec.dir)
- call append(3, '- Post-update hook for '. name .' ... ')
- let error = ''
- let type = type(spec.do)
- if type == s:TYPE.string
- if spec.do[0] == ':'
- call s:load_plugin(spec)
- try
- execute spec.do[1:]
- catch
- let error = v:exception
- endtry
- if !s:plug_window_exists()
- cd -
- throw 'Warning: vim-plug was terminated by the post-update hook of '.name
- endif
- else
- let error = s:bang(spec.do)
- endif
- elseif type == s:TYPE.funcref
- try
- let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged')
- call spec.do({ 'name': name, 'status': status, 'force': a:force })
- catch
- let error = v:exception
- endtry
- else
- let error = 'Invalid hook type'
- endif
- call s:switch_in()
- call setline(4, empty(error) ? (getline(4) . 'OK')
- \ : ('x' . getline(4)[1:] . error))
- if !empty(error)
- call add(s:update.errors, name)
- call s:regress_bar()
- endif
- cd -
- endif
- endfor
-endfunction
-
-function! s:hash_match(a, b)
- return stridx(a:a, a:b) == 0 || stridx(a:b, a:a) == 0
-endfunction
-
-function! s:checkout(spec)
- let sha = a:spec.commit
- let output = s:system('git rev-parse HEAD', a:spec.dir)
- if !v:shell_error && !s:hash_match(sha, s:lines(output)[0])
- let output = s:system(
- \ 'git fetch --depth 999999 && git checkout '.s:esc(sha), a:spec.dir)
- endif
- return output
-endfunction
-
-function! s:finish(pull)
- let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen'))
- if new_frozen
- let s = new_frozen > 1 ? 's' : ''
- call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s))
- endif
- call append(3, '- Finishing ... ') | 4
- redraw
- call plug#helptags()
- call plug#end()
- call setline(4, getline(4) . 'Done!')
- redraw
- let msgs = []
- if !empty(s:update.errors)
- call add(msgs, "Press 'R' to retry.")
- endif
- if a:pull && len(s:update.new) < len(filter(getline(5, '$'),
- \ "v:val =~ '^- ' && stridx(v:val, 'Already up-to-date') < 0"))
- call add(msgs, "Press 'D' to see the updated changes.")
- endif
- echo join(msgs, ' ')
- call s:finish_bindings()
-endfunction
-
-function! s:retry()
- if empty(s:update.errors)
- return
- endif
- echo
- call s:update_impl(s:update.pull, s:update.force,
- \ extend(copy(s:update.errors), [s:update.threads]))
-endfunction
-
-function! s:is_managed(name)
- return has_key(g:plugs[a:name], 'uri')
-endfunction
-
-function! s:names(...)
- return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)'))
-endfunction
-
-function! s:check_ruby()
- silent! ruby require 'thread'; VIM::command("let g:plug_ruby = '#{RUBY_VERSION}'")
- if !exists('g:plug_ruby')
- redraw!
- return s:warn('echom', 'Warning: Ruby interface is broken')
- endif
- let ruby_version = split(g:plug_ruby, '\.')
- unlet g:plug_ruby
- return s:version_requirement(ruby_version, [1, 8, 7])
-endfunction
-
-function! s:update_impl(pull, force, args) abort
- let args = copy(a:args)
- let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ?
- \ remove(args, -1) : get(g:, 'plug_threads', 16)
-
- let managed = filter(copy(g:plugs), 's:is_managed(v:key)')
- let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') :
- \ filter(managed, 'index(args, v:key) >= 0')
-
- if empty(todo)
- return s:warn('echo', 'No plugin to '. (a:pull ? 'update' : 'install'))
- endif
-
- if !s:is_win && s:git_version_requirement(2, 3)
- let s:git_terminal_prompt = exists('$GIT_TERMINAL_PROMPT') ? $GIT_TERMINAL_PROMPT : ''
- let $GIT_TERMINAL_PROMPT = 0
- for plug in values(todo)
- let plug.uri = substitute(plug.uri,
- \ '^https://git::@github\.com', 'https://github.com', '')
- endfor
- endif
-
- if !isdirectory(g:plug_home)
- try
- call mkdir(g:plug_home, 'p')
- catch
- return s:err(printf('Invalid plug directory: %s. '.
- \ 'Try to call plug#begin with a valid directory', g:plug_home))
- endtry
- endif
-
- if has('nvim') && !exists('*jobwait') && threads > 1
- call s:warn('echom', '[vim-plug] Update Neovim for parallel installer')
- endif
-
- let use_job = s:nvim || s:vim8
- let python = (has('python') || has('python3')) && !use_job
- let ruby = has('ruby') && !use_job && (v:version >= 703 || v:version == 702 && has('patch374')) && !(s:is_win && has('gui_running')) && s:check_ruby()
-
- let s:update = {
- \ 'start': reltime(),
- \ 'all': todo,
- \ 'todo': copy(todo),
- \ 'errors': [],
- \ 'pull': a:pull,
- \ 'force': a:force,
- \ 'new': {},
- \ 'threads': (python || ruby || use_job) ? min([len(todo), threads]) : 1,
- \ 'bar': '',
- \ 'fin': 0
- \ }
-
- call s:prepare(1)
- call append(0, ['', ''])
- normal! 2G
- silent! redraw
-
- let s:clone_opt = get(g:, 'plug_shallow', 1) ?
- \ '--depth 1' . (s:git_version_requirement(1, 7, 10) ? ' --no-single-branch' : '') : ''
-
- " Python version requirement (>= 2.7)
- if python && !has('python3') && !ruby && !use_job && s:update.threads > 1
- redir => pyv
- silent python import platform; print platform.python_version()
- redir END
- let python = s:version_requirement(
- \ map(split(split(pyv)[0], '\.'), 'str2nr(v:val)'), [2, 6])
- endif
-
- if (python || ruby) && s:update.threads > 1
- try
- let imd = &imd
- if s:mac_gui
- set noimd
- endif
- if ruby
- call s:update_ruby()
- else
- call s:update_python()
- endif
- catch
- let lines = getline(4, '$')
- let printed = {}
- silent! 4,$d _
- for line in lines
- let name = s:extract_name(line, '.', '')
- if empty(name) || !has_key(printed, name)
- call append('$', line)
- if !empty(name)
- let printed[name] = 1
- if line[0] == 'x' && index(s:update.errors, name) < 0
- call add(s:update.errors, name)
- end
- endif
- endif
- endfor
- finally
- let &imd = imd
- call s:update_finish()
- endtry
- else
- call s:update_vim()
- while use_job && has('vim_starting')
- sleep 100m
- if s:update.fin
- break
- endif
- endwhile
- endif
-endfunction
-
-function! s:log4(name, msg)
- call setline(4, printf('- %s (%s)', a:msg, a:name))
- redraw
-endfunction
-
-function! s:update_finish()
- if exists('s:git_terminal_prompt')
- let $GIT_TERMINAL_PROMPT = s:git_terminal_prompt
- endif
- if s:switch_in()
- call append(3, '- Updating ...') | 4
- for [name, spec] in items(filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && (s:update.force || s:update.pull || has_key(s:update.new, v:key))'))
- let [pos, _] = s:logpos(name)
- if !pos
- continue
- endif
- if has_key(spec, 'commit')
- call s:log4(name, 'Checking out '.spec.commit)
- let out = s:checkout(spec)
- elseif has_key(spec, 'tag')
- let tag = spec.tag
- if tag =~ '\*'
- let tags = s:lines(s:system('git tag --list '.string(tag).' --sort -version:refname 2>&1', spec.dir))
- if !v:shell_error && !empty(tags)
- let tag = tags[0]
- call s:log4(name, printf('Latest tag for %s -> %s', spec.tag, tag))
- call append(3, '')
- endif
- endif
- call s:log4(name, 'Checking out '.tag)
- let out = s:system('git checkout -q '.s:esc(tag).' 2>&1', spec.dir)
- else
- let branch = s:esc(get(spec, 'branch', 'master'))
- call s:log4(name, 'Merging origin/'.branch)
- let out = s:system('git checkout -q '.branch.' 2>&1'
- \. (has_key(s:update.new, name) ? '' : ('&& git merge --ff-only origin/'.branch.' 2>&1')), spec.dir)
- endif
- if !v:shell_error && filereadable(spec.dir.'/.gitmodules') &&
- \ (s:update.force || has_key(s:update.new, name) || s:is_updated(spec.dir))
- call s:log4(name, 'Updating submodules. This may take a while.')
- let out .= s:bang('git submodule update --init --recursive 2>&1', spec.dir)
- endif
- let msg = s:format_message(v:shell_error ? 'x': '-', name, out)
- if v:shell_error
- call add(s:update.errors, name)
- call s:regress_bar()
- silent execute pos 'd _'
- call append(4, msg) | 4
- elseif !empty(out)
- call setline(pos, msg[0])
- endif
- redraw
- endfor
- silent 4 d _
- try
- call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && has_key(v:val, "do")'))
- catch
- call s:warn('echom', v:exception)
- call s:warn('echo', '')
- return
- endtry
- call s:finish(s:update.pull)
- call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.')
- call s:switch_out('normal! gg')
- endif
-endfunction
-
-function! s:job_abort()
- if (!s:nvim && !s:vim8) || !exists('s:jobs')
- return
- endif
-
- for [name, j] in items(s:jobs)
- if s:nvim
- silent! call jobstop(j.jobid)
- elseif s:vim8
- silent! call job_stop(j.jobid)
- endif
- if j.new
- call s:system('rm -rf ' . s:shellesc(g:plugs[name].dir))
- endif
- endfor
- let s:jobs = {}
-endfunction
-
-function! s:last_non_empty_line(lines)
- let len = len(a:lines)
- for idx in range(len)
- let line = a:lines[len-idx-1]
- if !empty(line)
- return line
- endif
- endfor
- return ''
-endfunction
-
-function! s:job_out_cb(self, data) abort
- let self = a:self
- let data = remove(self.lines, -1) . a:data
- let lines = map(split(data, "\n", 1), 'split(v:val, "\r", 1)[-1]')
- call extend(self.lines, lines)
- " To reduce the number of buffer updates
- let self.tick = get(self, 'tick', -1) + 1
- if !self.running || self.tick % len(s:jobs) == 0
- let bullet = self.running ? (self.new ? '+' : '*') : (self.error ? 'x' : '-')
- let result = self.error ? join(self.lines, "\n") : s:last_non_empty_line(self.lines)
- call s:log(bullet, self.name, result)
- endif
-endfunction
-
-function! s:job_exit_cb(self, data) abort
- let a:self.running = 0
- let a:self.error = a:data != 0
- call s:reap(a:self.name)
- call s:tick()
-endfunction
-
-function! s:job_cb(fn, job, ch, data)
- if !s:plug_window_exists() " plug window closed
- return s:job_abort()
- endif
- call call(a:fn, [a:job, a:data])
-endfunction
-
-function! s:nvim_cb(job_id, data, event) abort
- return a:event == 'stdout' ?
- \ s:job_cb('s:job_out_cb', self, 0, join(a:data, "\n")) :
- \ s:job_cb('s:job_exit_cb', self, 0, a:data)
-endfunction
-
-function! s:spawn(name, cmd, opts)
- let job = { 'name': a:name, 'running': 1, 'error': 0, 'lines': [''],
- \ 'new': get(a:opts, 'new', 0) }
- let s:jobs[a:name] = job
- let argv = add(s:is_win ? ['cmd', '/c'] : ['sh', '-c'],
- \ has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir) : a:cmd)
-
- if s:nvim
- call extend(job, {
- \ 'on_stdout': function('s:nvim_cb'),
- \ 'on_exit': function('s:nvim_cb'),
- \ })
- let jid = jobstart(argv, job)
- if jid > 0
- let job.jobid = jid
- else
- let job.running = 0
- let job.error = 1
- let job.lines = [jid < 0 ? argv[0].' is not executable' :
- \ 'Invalid arguments (or job table is full)']
- endif
- elseif s:vim8
- let jid = job_start(argv, {
- \ 'out_cb': function('s:job_cb', ['s:job_out_cb', job]),
- \ 'exit_cb': function('s:job_cb', ['s:job_exit_cb', job]),
- \ 'out_mode': 'raw'
- \})
- if job_status(jid) == 'run'
- let job.jobid = jid
- else
- let job.running = 0
- let job.error = 1
- let job.lines = ['Failed to start job']
- endif
- else
- let params = has_key(a:opts, 'dir') ? [a:cmd, a:opts.dir] : [a:cmd]
- let job.lines = s:lines(call('s:system', params))
- let job.error = v:shell_error != 0
- let job.running = 0
- endif
-endfunction
-
-function! s:reap(name)
- let job = s:jobs[a:name]
- if job.error
- call add(s:update.errors, a:name)
- elseif get(job, 'new', 0)
- let s:update.new[a:name] = 1
- endif
- let s:update.bar .= job.error ? 'x' : '='
-
- let bullet = job.error ? 'x' : '-'
- let result = job.error ? join(job.lines, "\n") : s:last_non_empty_line(job.lines)
- call s:log(bullet, a:name, empty(result) ? 'OK' : result)
- call s:bar()
-
- call remove(s:jobs, a:name)
-endfunction
-
-function! s:bar()
- if s:switch_in()
- let total = len(s:update.all)
- call setline(1, (s:update.pull ? 'Updating' : 'Installing').
- \ ' plugins ('.len(s:update.bar).'/'.total.')')
- call s:progress_bar(2, s:update.bar, total)
- call s:switch_out()
- endif
-endfunction
-
-function! s:logpos(name)
- for i in range(4, line('$'))
- if getline(i) =~# '^[-+x*] '.a:name.':'
- for j in range(i + 1, line('$'))
- if getline(j) !~ '^ '
- return [i, j - 1]
- endif
- endfor
- return [i, i]
- endif
- endfor
- return [0, 0]
-endfunction
-
-function! s:log(bullet, name, lines)
- if s:switch_in()
- let [b, e] = s:logpos(a:name)
- if b > 0
- silent execute printf('%d,%d d _', b, e)
- if b > winheight('.')
- let b = 4
- endif
- else
- let b = 4
- endif
- " FIXME For some reason, nomodifiable is set after :d in vim8
- setlocal modifiable
- call append(b - 1, s:format_message(a:bullet, a:name, a:lines))
- call s:switch_out()
- endif
-endfunction
-
-function! s:update_vim()
- let s:jobs = {}
-
- call s:bar()
- call s:tick()
-endfunction
-
-function! s:tick()
- let pull = s:update.pull
- let prog = s:progress_opt(s:nvim || s:vim8)
-while 1 " Without TCO, Vim stack is bound to explode
- if empty(s:update.todo)
- if empty(s:jobs) && !s:update.fin
- call s:update_finish()
- let s:update.fin = 1
- endif
- return
- endif
-
- let name = keys(s:update.todo)[0]
- let spec = remove(s:update.todo, name)
- let new = !isdirectory(spec.dir)
-
- call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...')
- redraw
-
- let has_tag = has_key(spec, 'tag')
- if !new
- let [error, _] = s:git_validate(spec, 0)
- if empty(error)
- if pull
- let fetch_opt = (has_tag && !empty(globpath(spec.dir, '.git/shallow'))) ? '--depth 99999999' : ''
- call s:spawn(name, printf('git fetch %s %s 2>&1', fetch_opt, prog), { 'dir': spec.dir })
- else
- let s:jobs[name] = { 'running': 0, 'lines': ['Already installed'], 'error': 0 }
- endif
- else
- let s:jobs[name] = { 'running': 0, 'lines': s:lines(error), 'error': 1 }
- endif
- else
- call s:spawn(name,
- \ printf('git clone %s %s %s %s 2>&1',
- \ has_tag ? '' : s:clone_opt,
- \ prog,
- \ s:shellesc(spec.uri),
- \ s:shellesc(s:trim(spec.dir))), { 'new': 1 })
- endif
-
- if !s:jobs[name].running
- call s:reap(name)
- endif
- if len(s:jobs) >= s:update.threads
- break
- endif
-endwhile
-endfunction
-
-function! s:update_python()
-let py_exe = has('python') ? 'python' : 'python3'
-execute py_exe "<< EOF"
-import datetime
-import functools
-import os
-try:
- import queue
-except ImportError:
- import Queue as queue
-import random
-import re
-import shutil
-import signal
-import subprocess
-import tempfile
-import threading as thr
-import time
-import traceback
-import vim
-
-G_NVIM = vim.eval("has('nvim')") == '1'
-G_PULL = vim.eval('s:update.pull') == '1'
-G_RETRIES = int(vim.eval('get(g:, "plug_retries", 2)')) + 1
-G_TIMEOUT = int(vim.eval('get(g:, "plug_timeout", 60)'))
-G_CLONE_OPT = vim.eval('s:clone_opt')
-G_PROGRESS = vim.eval('s:progress_opt(1)')
-G_LOG_PROB = 1.0 / int(vim.eval('s:update.threads'))
-G_STOP = thr.Event()
-G_IS_WIN = vim.eval('s:is_win') == '1'
-
-class PlugError(Exception):
- def __init__(self, msg):
- self.msg = msg
-class CmdTimedOut(PlugError):
- pass
-class CmdFailed(PlugError):
- pass
-class InvalidURI(PlugError):
- pass
-class Action(object):
- INSTALL, UPDATE, ERROR, DONE = ['+', '*', 'x', '-']
-
-class Buffer(object):
- def __init__(self, lock, num_plugs, is_pull):
- self.bar = ''
- self.event = 'Updating' if is_pull else 'Installing'
- self.lock = lock
- self.maxy = int(vim.eval('winheight(".")'))
- self.num_plugs = num_plugs
-
- def __where(self, name):
- """ Find first line with name in current buffer. Return line num. """
- found, lnum = False, 0
- matcher = re.compile('^[-+x*] {0}:'.format(name))
- for line in vim.current.buffer:
- if matcher.search(line) is not None:
- found = True
- break
- lnum += 1
-
- if not found:
- lnum = -1
- return lnum
-
- def header(self):
- curbuf = vim.current.buffer
- curbuf[0] = self.event + ' plugins ({0}/{1})'.format(len(self.bar), self.num_plugs)
-
- num_spaces = self.num_plugs - len(self.bar)
- curbuf[1] = '[{0}{1}]'.format(self.bar, num_spaces * ' ')
-
- with self.lock:
- vim.command('normal! 2G')
- vim.command('redraw')
-
- def write(self, action, name, lines):
- first, rest = lines[0], lines[1:]
- msg = ['{0} {1}{2}{3}'.format(action, name, ': ' if first else '', first)]
- msg.extend([' ' + line for line in rest])
-
- try:
- if action == Action.ERROR:
- self.bar += 'x'
- vim.command("call add(s:update.errors, '{0}')".format(name))
- elif action == Action.DONE:
- self.bar += '='
-
- curbuf = vim.current.buffer
- lnum = self.__where(name)
- if lnum != -1: # Found matching line num
- del curbuf[lnum]
- if lnum > self.maxy and action in set([Action.INSTALL, Action.UPDATE]):
- lnum = 3
- else:
- lnum = 3
- curbuf.append(msg, lnum)
-
- self.header()
- except vim.error:
- pass
-
-class Command(object):
- CD = 'cd /d' if G_IS_WIN else 'cd'
-
- def __init__(self, cmd, cmd_dir=None, timeout=60, cb=None, clean=None):
- self.cmd = cmd
- if cmd_dir:
- self.cmd = '{0} {1} && {2}'.format(Command.CD, cmd_dir, self.cmd)
- self.timeout = timeout
- self.callback = cb if cb else (lambda msg: None)
- self.clean = clean if clean else (lambda: None)
- self.proc = None
-
- @property
- def alive(self):
- """ Returns true only if command still running. """
- return self.proc and self.proc.poll() is None
-
- def execute(self, ntries=3):
- """ Execute the command with ntries if CmdTimedOut.
- Returns the output of the command if no Exception.
- """
- attempt, finished, limit = 0, False, self.timeout
-
- while not finished:
- try:
- attempt += 1
- result = self.try_command()
- finished = True
- return result
- except CmdTimedOut:
- if attempt != ntries:
- self.notify_retry()
- self.timeout += limit
- else:
- raise
-
- def notify_retry(self):
- """ Retry required for command, notify user. """
- for count in range(3, 0, -1):
- if G_STOP.is_set():
- raise KeyboardInterrupt
- msg = 'Timeout. Will retry in {0} second{1} ...'.format(
- count, 's' if count != 1 else '')
- self.callback([msg])
- time.sleep(1)
- self.callback(['Retrying ...'])
-
- def try_command(self):
- """ Execute a cmd & poll for callback. Returns list of output.
- Raises CmdFailed -> return code for Popen isn't 0
- Raises CmdTimedOut -> command exceeded timeout without new output
- """
- first_line = True
-
- try:
- tfile = tempfile.NamedTemporaryFile(mode='w+b')
- preexec_fn = not G_IS_WIN and os.setsid or None
- self.proc = subprocess.Popen(self.cmd, stdout=tfile,
- stderr=subprocess.STDOUT,
- stdin=subprocess.PIPE, shell=True,
- preexec_fn=preexec_fn)
- thrd = thr.Thread(target=(lambda proc: proc.wait()), args=(self.proc,))
- thrd.start()
-
- thread_not_started = True
- while thread_not_started:
- try:
- thrd.join(0.1)
- thread_not_started = False
- except RuntimeError:
- pass
-
- while self.alive:
- if G_STOP.is_set():
- raise KeyboardInterrupt
-
- if first_line or random.random() < G_LOG_PROB:
- first_line = False
- line = '' if G_IS_WIN else nonblock_read(tfile.name)
- if line:
- self.callback([line])
-
- time_diff = time.time() - os.path.getmtime(tfile.name)
- if time_diff > self.timeout:
- raise CmdTimedOut(['Timeout!'])
-
- thrd.join(0.5)
-
- tfile.seek(0)
- result = [line.decode('utf-8', 'replace').rstrip() for line in tfile]
-
- if self.proc.returncode != 0:
- raise CmdFailed([''] + result)
-
- return result
- except:
- self.terminate()
- raise
-
- def terminate(self):
- """ Terminate process and cleanup. """
- if self.alive:
- if G_IS_WIN:
- os.kill(self.proc.pid, signal.SIGINT)
- else:
- os.killpg(self.proc.pid, signal.SIGTERM)
- self.clean()
-
-class Plugin(object):
- def __init__(self, name, args, buf_q, lock):
- self.name = name
- self.args = args
- self.buf_q = buf_q
- self.lock = lock
- self.tag = args.get('tag', 0)
-
- def manage(self):
- try:
- if os.path.exists(self.args['dir']):
- self.update()
- else:
- self.install()
- with self.lock:
- thread_vim_command("let s:update.new['{0}'] = 1".format(self.name))
- except PlugError as exc:
- self.write(Action.ERROR, self.name, exc.msg)
- except KeyboardInterrupt:
- G_STOP.set()
- self.write(Action.ERROR, self.name, ['Interrupted!'])
- except:
- # Any exception except those above print stack trace
- msg = 'Trace:\n{0}'.format(traceback.format_exc().rstrip())
- self.write(Action.ERROR, self.name, msg.split('\n'))
- raise
-
- def install(self):
- target = self.args['dir']
- if target[-1] == '\\':
- target = target[0:-1]
-
- def clean(target):
- def _clean():
- try:
- shutil.rmtree(target)
- except OSError:
- pass
- return _clean
-
- self.write(Action.INSTALL, self.name, ['Installing ...'])
- callback = functools.partial(self.write, Action.INSTALL, self.name)
- cmd = 'git clone {0} {1} {2} {3} 2>&1'.format(
- '' if self.tag else G_CLONE_OPT, G_PROGRESS, self.args['uri'],
- esc(target))
- com = Command(cmd, None, G_TIMEOUT, callback, clean(target))
- result = com.execute(G_RETRIES)
- self.write(Action.DONE, self.name, result[-1:])
-
- def repo_uri(self):
- cmd = 'git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url'
- command = Command(cmd, self.args['dir'], G_TIMEOUT,)
- result = command.execute(G_RETRIES)
- return result[-1]
-
- def update(self):
- actual_uri = self.repo_uri()
- expect_uri = self.args['uri']
- regex = re.compile(r'^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$')
- ma = regex.match(actual_uri)
- mb = regex.match(expect_uri)
- if ma is None or mb is None or ma.groups() != mb.groups():
- msg = ['',
- 'Invalid URI: {0}'.format(actual_uri),
- 'Expected {0}'.format(expect_uri),
- 'PlugClean required.']
- raise InvalidURI(msg)
-
- if G_PULL:
- self.write(Action.UPDATE, self.name, ['Updating ...'])
- callback = functools.partial(self.write, Action.UPDATE, self.name)
- fetch_opt = '--depth 99999999' if self.tag and os.path.isfile(os.path.join(self.args['dir'], '.git/shallow')) else ''
- cmd = 'git fetch {0} {1} 2>&1'.format(fetch_opt, G_PROGRESS)
- com = Command(cmd, self.args['dir'], G_TIMEOUT, callback)
- result = com.execute(G_RETRIES)
- self.write(Action.DONE, self.name, result[-1:])
- else:
- self.write(Action.DONE, self.name, ['Already installed'])
-
- def write(self, action, name, msg):
- self.buf_q.put((action, name, msg))
-
-class PlugThread(thr.Thread):
- def __init__(self, tname, args):
- super(PlugThread, self).__init__()
- self.tname = tname
- self.args = args
-
- def run(self):
- thr.current_thread().name = self.tname
- buf_q, work_q, lock = self.args
-
- try:
- while not G_STOP.is_set():
- name, args = work_q.get_nowait()
- plug = Plugin(name, args, buf_q, lock)
- plug.manage()
- work_q.task_done()
- except queue.Empty:
- pass
-
-class RefreshThread(thr.Thread):
- def __init__(self, lock):
- super(RefreshThread, self).__init__()
- self.lock = lock
- self.running = True
-
- def run(self):
- while self.running:
- with self.lock:
- thread_vim_command('noautocmd normal! a')
- time.sleep(0.33)
-
- def stop(self):
- self.running = False
-
-if G_NVIM:
- def thread_vim_command(cmd):
- vim.session.threadsafe_call(lambda: vim.command(cmd))
-else:
- def thread_vim_command(cmd):
- vim.command(cmd)
-
-def esc(name):
- return '"' + name.replace('"', '\"') + '"'
-
-def nonblock_read(fname):
- """ Read a file with nonblock flag. Return the last line. """
- fread = os.open(fname, os.O_RDONLY | os.O_NONBLOCK)
- buf = os.read(fread, 100000).decode('utf-8', 'replace')
- os.close(fread)
-
- line = buf.rstrip('\r\n')
- left = max(line.rfind('\r'), line.rfind('\n'))
- if left != -1:
- left += 1
- line = line[left:]
-
- return line
-
-def main():
- thr.current_thread().name = 'main'
- nthreads = int(vim.eval('s:update.threads'))
- plugs = vim.eval('s:update.todo')
- mac_gui = vim.eval('s:mac_gui') == '1'
-
- lock = thr.Lock()
- buf = Buffer(lock, len(plugs), G_PULL)
- buf_q, work_q = queue.Queue(), queue.Queue()
- for work in plugs.items():
- work_q.put(work)
-
- start_cnt = thr.active_count()
- for num in range(nthreads):
- tname = 'PlugT-{0:02}'.format(num)
- thread = PlugThread(tname, (buf_q, work_q, lock))
- thread.start()
- if mac_gui:
- rthread = RefreshThread(lock)
- rthread.start()
-
- while not buf_q.empty() or thr.active_count() != start_cnt:
- try:
- action, name, msg = buf_q.get(True, 0.25)
- buf.write(action, name, ['OK'] if not msg else msg)
- buf_q.task_done()
- except queue.Empty:
- pass
- except KeyboardInterrupt:
- G_STOP.set()
-
- if mac_gui:
- rthread.stop()
- rthread.join()
-
-main()
-EOF
-endfunction
-
-function! s:update_ruby()
- ruby << EOF
- module PlugStream
- SEP = ["\r", "\n", nil]
- def get_line
- buffer = ''
- loop do
- char = readchar rescue return
- if SEP.include? char.chr
- buffer << $/
- break
- else
- buffer << char
- end
- end
- buffer
- end
- end unless defined?(PlugStream)
-
- def esc arg
- %["#{arg.gsub('"', '\"')}"]
- end
-
- def killall pid
- pids = [pid]
- if /mswin|mingw|bccwin/ =~ RUBY_PLATFORM
- pids.each { |pid| Process.kill 'INT', pid.to_i rescue nil }
- else
- unless `which pgrep 2> /dev/null`.empty?
- children = pids
- until children.empty?
- children = children.map { |pid|
- `pgrep -P #{pid}`.lines.map { |l| l.chomp }
- }.flatten
- pids += children
- end
- end
- pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil }
- end
- end
-
- def compare_git_uri a, b
- regex = %r{^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$}
- regex.match(a).to_a.drop(1) == regex.match(b).to_a.drop(1)
- end
-
- require 'thread'
- require 'fileutils'
- require 'timeout'
- running = true
- iswin = VIM::evaluate('s:is_win').to_i == 1
- pull = VIM::evaluate('s:update.pull').to_i == 1
- base = VIM::evaluate('g:plug_home')
- all = VIM::evaluate('s:update.todo')
- limit = VIM::evaluate('get(g:, "plug_timeout", 60)')
- tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1
- nthr = VIM::evaluate('s:update.threads').to_i
- maxy = VIM::evaluate('winheight(".")').to_i
- cd = iswin ? 'cd /d' : 'cd'
- tot = VIM::evaluate('len(s:update.todo)') || 0
- bar = ''
- skip = 'Already installed'
- mtx = Mutex.new
- take1 = proc { mtx.synchronize { running && all.shift } }
- logh = proc {
- cnt = bar.length
- $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})"
- $curbuf[2] = '[' + bar.ljust(tot) + ']'
- VIM::command('normal! 2G')
- VIM::command('redraw')
- }
- where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } }
- log = proc { |name, result, type|
- mtx.synchronize do
- ing = ![true, false].include?(type)
- bar += type ? '=' : 'x' unless ing
- b = case type
- when :install then '+' when :update then '*'
- when true, nil then '-' else
- VIM::command("call add(s:update.errors, '#{name}')")
- 'x'
- end
- result =
- if type || type.nil?
- ["#{b} #{name}: #{result.lines.to_a.last || 'OK'}"]
- elsif result =~ /^Interrupted|^Timeout/
- ["#{b} #{name}: #{result}"]
- else
- ["#{b} #{name}"] + result.lines.map { |l| " " << l }
- end
- if lnum = where.call(name)
- $curbuf.delete lnum
- lnum = 4 if ing && lnum > maxy
- end
- result.each_with_index do |line, offset|
- $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp)
- end
- logh.call
- end
- }
- bt = proc { |cmd, name, type, cleanup|
- tried = timeout = 0
- begin
- tried += 1
- timeout += limit
- fd = nil
- data = ''
- if iswin
- Timeout::timeout(timeout) do
- tmp = VIM::evaluate('tempname()')
- system("(#{cmd}) > #{tmp}")
- data = File.read(tmp).chomp
- File.unlink tmp rescue nil
- end
- else
- fd = IO.popen(cmd).extend(PlugStream)
- first_line = true
- log_prob = 1.0 / nthr
- while line = Timeout::timeout(timeout) { fd.get_line }
- data << line
- log.call name, line.chomp, type if name && (first_line || rand < log_prob)
- first_line = false
- end
- fd.close
- end
- [$? == 0, data.chomp]
- rescue Timeout::Error, Interrupt => e
- if fd && !fd.closed?
- killall fd.pid
- fd.close
- end
- cleanup.call if cleanup
- if e.is_a?(Timeout::Error) && tried < tries
- 3.downto(1) do |countdown|
- s = countdown > 1 ? 's' : ''
- log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type
- sleep 1
- end
- log.call name, 'Retrying ...', type
- retry
- end
- [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"]
- end
- }
- main = Thread.current
- threads = []
- watcher = Thread.new {
- require 'io/console' # >= Ruby 1.9
- nil until IO.console.getch == 3.chr
- mtx.synchronize do
- running = false
- threads.each { |t| t.raise Interrupt }
- end
- threads.each { |t| t.join rescue nil }
- main.kill
- }
- refresh = Thread.new {
- while true
- mtx.synchronize do
- break unless running
- VIM::command('noautocmd normal! a')
- end
- sleep 0.2
- end
- } if VIM::evaluate('s:mac_gui') == 1
-
- clone_opt = VIM::evaluate('s:clone_opt')
- progress = VIM::evaluate('s:progress_opt(1)')
- nthr.times do
- mtx.synchronize do
- threads << Thread.new {
- while pair = take1.call
- name = pair.first
- dir, uri, tag = pair.last.values_at *%w[dir uri tag]
- exists = File.directory? dir
- ok, result =
- if exists
- chdir = "#{cd} #{iswin ? dir : esc(dir)}"
- ret, data = bt.call "#{chdir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url", nil, nil, nil
- current_uri = data.lines.to_a.last
- if !ret
- if data =~ /^Interrupted|^Timeout/
- [false, data]
- else
- [false, [data.chomp, "PlugClean required."].join($/)]
- end
- elsif !compare_git_uri(current_uri, uri)
- [false, ["Invalid URI: #{current_uri}",
- "Expected: #{uri}",
- "PlugClean required."].join($/)]
- else
- if pull
- log.call name, 'Updating ...', :update
- fetch_opt = (tag && File.exist?(File.join(dir, '.git/shallow'))) ? '--depth 99999999' : ''
- bt.call "#{chdir} && git fetch #{fetch_opt} #{progress} 2>&1", name, :update, nil
- else
- [true, skip]
- end
- end
- else
- d = esc dir.sub(%r{[\\/]+$}, '')
- log.call name, 'Installing ...', :install
- bt.call "git clone #{clone_opt unless tag} #{progress} #{uri} #{d} 2>&1", name, :install, proc {
- FileUtils.rm_rf dir
- }
- end
- mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok
- log.call name, result, ok
- end
- } if running
- end
- end
- threads.each { |t| t.join rescue nil }
- logh.call
- refresh.kill if refresh
- watcher.kill
-EOF
-endfunction
-
-function! s:shellesc(arg)
- return '"'.escape(a:arg, '"').'"'
-endfunction
-
-function! s:glob_dir(path)
- return map(filter(s:glob(a:path, '**'), 'isdirectory(v:val)'), 's:dirpath(v:val)')
-endfunction
-
-function! s:progress_bar(line, bar, total)
- call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']')
-endfunction
-
-function! s:compare_git_uri(a, b)
- " See `git help clone'
- " https:// [user@] github.com[:port] / junegunn/vim-plug [.git]
- " [git@] github.com[:port] : junegunn/vim-plug [.git]
- " file:// / junegunn/vim-plug [/]
- " / junegunn/vim-plug [/]
- let pat = '^\%(\w\+://\)\='.'\%([^@/]*@\)\='.'\([^:/]*\%(:[0-9]*\)\=\)'.'[:/]'.'\(.\{-}\)'.'\%(\.git\)\=/\?$'
- let ma = matchlist(a:a, pat)
- let mb = matchlist(a:b, pat)
- return ma[1:2] ==# mb[1:2]
-endfunction
-
-function! s:format_message(bullet, name, message)
- if a:bullet != 'x'
- return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))]
- else
- let lines = map(s:lines(a:message), '" ".v:val')
- return extend([printf('x %s:', a:name)], lines)
- endif
-endfunction
-
-function! s:with_cd(cmd, dir)
- return printf('cd%s %s && %s', s:is_win ? ' /d' : '', s:shellesc(a:dir), a:cmd)
-endfunction
-
-function! s:system(cmd, ...)
- try
- let [sh, shrd] = s:chsh(1)
- let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd
- return system(s:is_win ? '('.cmd.')' : cmd)
- finally
- let [&shell, &shellredir] = [sh, shrd]
- endtry
-endfunction
-
-function! s:system_chomp(...)
- let ret = call('s:system', a:000)
- return v:shell_error ? '' : substitute(ret, '\n$', '', '')
-endfunction
-
-function! s:git_validate(spec, check_branch)
- let err = ''
- if isdirectory(a:spec.dir)
- let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url', a:spec.dir))
- let remote = result[-1]
- if v:shell_error
- let err = join([remote, 'PlugClean required.'], "\n")
- elseif !s:compare_git_uri(remote, a:spec.uri)
- let err = join(['Invalid URI: '.remote,
- \ 'Expected: '.a:spec.uri,
- \ 'PlugClean required.'], "\n")
- elseif a:check_branch && has_key(a:spec, 'commit')
- let result = s:lines(s:system('git rev-parse HEAD 2>&1', a:spec.dir))
- let sha = result[-1]
- if v:shell_error
- let err = join(add(result, 'PlugClean required.'), "\n")
- elseif !s:hash_match(sha, a:spec.commit)
- let err = join([printf('Invalid HEAD (expected: %s, actual: %s)',
- \ a:spec.commit[:6], sha[:6]),
- \ 'PlugUpdate required.'], "\n")
- endif
- elseif a:check_branch
- let branch = result[0]
- " Check tag
- if has_key(a:spec, 'tag')
- let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir)
- if a:spec.tag !=# tag
- let err = printf('Invalid tag: %s (expected: %s). Try PlugUpdate.',
- \ (empty(tag) ? 'N/A' : tag), a:spec.tag)
- endif
- " Check branch
- elseif a:spec.branch !=# branch
- let err = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.',
- \ branch, a:spec.branch)
- endif
- if empty(err)
- let commits = len(s:lines(s:system(printf('git rev-list origin/%s..HEAD', a:spec.branch), a:spec.dir)))
- if !v:shell_error && commits
- let err = join([printf('Diverged from origin/%s by %d commit(s).', a:spec.branch, commits),
- \ 'Reinstall after PlugClean.'], "\n")
- endif
- endif
- endif
- else
- let err = 'Not found'
- endif
- return [err, err =~# 'PlugClean']
-endfunction
-
-function! s:rm_rf(dir)
- if isdirectory(a:dir)
- call s:system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(a:dir))
- endif
-endfunction
-
-function! s:clean(force)
- call s:prepare()
- call append(0, 'Searching for invalid plugins in '.g:plug_home)
- call append(1, '')
-
- " List of valid directories
- let dirs = []
- let errs = {}
- let [cnt, total] = [0, len(g:plugs)]
- for [name, spec] in items(g:plugs)
- if !s:is_managed(name)
- call add(dirs, spec.dir)
- else
- let [err, clean] = s:git_validate(spec, 1)
- if clean
- let errs[spec.dir] = s:lines(err)[0]
- else
- call add(dirs, spec.dir)
- endif
- endif
- let cnt += 1
- call s:progress_bar(2, repeat('=', cnt), total)
- normal! 2G
- redraw
- endfor
-
- let allowed = {}
- for dir in dirs
- let allowed[s:dirpath(fnamemodify(dir, ':h:h'))] = 1
- let allowed[dir] = 1
- for child in s:glob_dir(dir)
- let allowed[child] = 1
- endfor
- endfor
-
- let todo = []
- let found = sort(s:glob_dir(g:plug_home))
- while !empty(found)
- let f = remove(found, 0)
- if !has_key(allowed, f) && isdirectory(f)
- call add(todo, f)
- call append(line('$'), '- ' . f)
- if has_key(errs, f)
- call append(line('$'), ' ' . errs[f])
- endif
- let found = filter(found, 'stridx(v:val, f) != 0')
- end
- endwhile
-
- 4
- redraw
- if empty(todo)
- call append(line('$'), 'Already clean.')
- else
- let s:clean_count = 0
- call append(3, ['Directories to delete:', ''])
- redraw!
- if a:force || s:ask_no_interrupt('Delete all directories?')
- call s:delete([6, line('$')], 1)
- else
- call setline(4, 'Cancelled.')
- nnoremap <silent> <buffer> d :set opfunc=<sid>delete_op<cr>g@
- nmap <silent> <buffer> dd d_
- xnoremap <silent> <buffer> d :<c-u>call <sid>delete_op(visualmode(), 1)<cr>
- echo 'Delete the lines (d{motion}) to delete the corresponding directories'
- endif
- endif
- 4
- setlocal nomodifiable
-endfunction
-
-function! s:delete_op(type, ...)
- call s:delete(a:0 ? [line("'<"), line("'>")] : [line("'["), line("']")], 0)
-endfunction
-
-function! s:delete(range, force)
- let [l1, l2] = a:range
- let force = a:force
- while l1 <= l2
- let line = getline(l1)
- if line =~ '^- ' && isdirectory(line[2:])
- execute l1
- redraw!
- let answer = force ? 1 : s:ask('Delete '.line[2:].'?', 1)
- let force = force || answer > 1
- if answer
- call s:rm_rf(line[2:])
- setlocal modifiable
- call setline(l1, '~'.line[1:])
- let s:clean_count += 1
- call setline(4, printf('Removed %d directories.', s:clean_count))
- setlocal nomodifiable
- endif
- endif
- let l1 += 1
- endwhile
-endfunction
-
-function! s:upgrade()
- echo 'Downloading the latest version of vim-plug'
- redraw
- let tmp = tempname()
- let new = tmp . '/plug.vim'
-
- try
- let out = s:system(printf('git clone --depth 1 %s %s', s:plug_src, tmp))
- if v:shell_error
- return s:err('Error upgrading vim-plug: '. out)
- endif
-
- if readfile(s:me) ==# readfile(new)
- echo 'vim-plug is already up-to-date'
- return 0
- else
- call rename(s:me, s:me . '.old')
- call rename(new, s:me)
- unlet g:loaded_plug
- echo 'vim-plug has been upgraded'
- return 1
- endif
- finally
- silent! call s:rm_rf(tmp)
- endtry
-endfunction
-
-function! s:upgrade_specs()
- for spec in values(g:plugs)
- let spec.frozen = get(spec, 'frozen', 0)
- endfor
-endfunction
-
-function! s:status()
- call s:prepare()
- call append(0, 'Checking plugins')
- call append(1, '')
-
- let ecnt = 0
- let unloaded = 0
- let [cnt, total] = [0, len(g:plugs)]
- for [name, spec] in items(g:plugs)
- if has_key(spec, 'uri')
- if isdirectory(spec.dir)
- let [err, _] = s:git_validate(spec, 1)
- let [valid, msg] = [empty(err), empty(err) ? 'OK' : err]
- else
- let [valid, msg] = [0, 'Not found. Try PlugInstall.']
- endif
- else
- if isdirectory(spec.dir)
- let [valid, msg] = [1, 'OK']
- else
- let [valid, msg] = [0, 'Not found.']
- endif
- endif
- let cnt += 1
- let ecnt += !valid
- " `s:loaded` entry can be missing if PlugUpgraded
- if valid && get(s:loaded, name, -1) == 0
- let unloaded = 1
- let msg .= ' (not loaded)'
- endif
- call s:progress_bar(2, repeat('=', cnt), total)
- call append(3, s:format_message(valid ? '-' : 'x', name, msg))
- normal! 2G
- redraw
- endfor
- call setline(1, 'Finished. '.ecnt.' error(s).')
- normal! gg
- setlocal nomodifiable
- if unloaded
- echo "Press 'L' on each line to load plugin, or 'U' to update"
- nnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
- xnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
- end
-endfunction
-
-function! s:extract_name(str, prefix, suffix)
- return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$')
-endfunction
-
-function! s:status_load(lnum)
- let line = getline(a:lnum)
- let name = s:extract_name(line, '-', '(not loaded)')
- if !empty(name)
- call plug#load(name)
- setlocal modifiable
- call setline(a:lnum, substitute(line, ' (not loaded)$', '', ''))
- setlocal nomodifiable
- endif
-endfunction
-
-function! s:status_update() range
- let lines = getline(a:firstline, a:lastline)
- let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)')
- if !empty(names)
- echo
- execute 'PlugUpdate' join(names)
- endif
-endfunction
-
-function! s:is_preview_window_open()
- silent! wincmd P
- if &previewwindow
- wincmd p
- return 1
- endif
-endfunction
-
-function! s:find_name(lnum)
- for lnum in reverse(range(1, a:lnum))
- let line = getline(lnum)
- if empty(line)
- return ''
- endif
- let name = s:extract_name(line, '-', '')
- if !empty(name)
- return name
- endif
- endfor
- return ''
-endfunction
-
-function! s:preview_commit()
- if b:plug_preview < 0
- let b:plug_preview = !s:is_preview_window_open()
- endif
-
- let sha = matchstr(getline('.'), '^ \X*\zs[0-9a-f]\{7}')
- if empty(sha)
- return
- endif
-
- let name = s:find_name(line('.'))
- if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir)
- return
- endif
-
- if exists('g:plug_pwindow') && !s:is_preview_window_open()
- execute g:plug_pwindow
- execute 'e' sha
- else
- execute 'pedit' sha
- wincmd P
- endif
- setlocal previewwindow filetype=git buftype=nofile nobuflisted modifiable
- execute 'silent %!cd' s:shellesc(g:plugs[name].dir) '&& git show --no-color --pretty=medium' sha
- setlocal nomodifiable
- nnoremap <silent> <buffer> q :q<cr>
- wincmd p
-endfunction
-
-function! s:section(flags)
- call search('\(^[x-] \)\@<=[^:]\+:', a:flags)
-endfunction
-
-function! s:format_git_log(line)
- let indent = ' '
- let tokens = split(a:line, nr2char(1))
- if len(tokens) != 5
- return indent.substitute(a:line, '\s*$', '', '')
- endif
- let [graph, sha, refs, subject, date] = tokens
- let tag = matchstr(refs, 'tag: [^,)]\+')
- let tag = empty(tag) ? ' ' : ' ('.tag.') '
- return printf('%s%s%s%s%s (%s)', indent, graph, sha, tag, subject, date)
-endfunction
-
-function! s:append_ul(lnum, text)
- call append(a:lnum, ['', a:text, repeat('-', len(a:text))])
-endfunction
-
-function! s:diff()
- call s:prepare()
- call append(0, ['Collecting changes ...', ''])
- let cnts = [0, 0]
- let bar = ''
- let total = filter(copy(g:plugs), 's:is_managed(v:key) && isdirectory(v:val.dir)')
- call s:progress_bar(2, bar, len(total))
- for origin in [1, 0]
- let plugs = reverse(sort(items(filter(copy(total), (origin ? '' : '!').'(has_key(v:val, "commit") || has_key(v:val, "tag"))'))))
- if empty(plugs)
- continue
- endif
- call s:append_ul(2, origin ? 'Pending updates:' : 'Last update:')
- for [k, v] in plugs
- let range = origin ? '..origin/'.v.branch : 'HEAD@{1}..'
- let diff = s:system_chomp('git log --graph --color=never --pretty=format:"%x01%h%x01%d%x01%s%x01%cr" '.s:shellesc(range), v.dir)
- if !empty(diff)
- let ref = has_key(v, 'tag') ? (' (tag: '.v.tag.')') : has_key(v, 'commit') ? (' '.v.commit) : ''
- call append(5, extend(['', '- '.k.':'.ref], map(s:lines(diff), 's:format_git_log(v:val)')))
- let cnts[origin] += 1
- endif
- let bar .= '='
- call s:progress_bar(2, bar, len(total))
- normal! 2G
- redraw
- endfor
- if !cnts[origin]
- call append(5, ['', 'N/A'])
- endif
- endfor
- call setline(1, printf('%d plugin(s) updated.', cnts[0])
- \ . (cnts[1] ? printf(' %d plugin(s) have pending updates.', cnts[1]) : ''))
-
- if cnts[0] || cnts[1]
- nnoremap <silent> <buffer> <cr> :silent! call <SID>preview_commit()<cr>
- nnoremap <silent> <buffer> o :silent! call <SID>preview_commit()<cr>
- endif
- if cnts[0]
- nnoremap <silent> <buffer> X :call <SID>revert()<cr>
- echo "Press 'X' on each block to revert the update"
- endif
- normal! gg
- setlocal nomodifiable
-endfunction
-
-function! s:revert()
- if search('^Pending updates', 'bnW')
- return
- endif
-
- let name = s:find_name(line('.'))
- if empty(name) || !has_key(g:plugs, name) ||
- \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y'
- return
- endif
-
- call s:system('git reset --hard HEAD@{1} && git checkout '.s:esc(g:plugs[name].branch), g:plugs[name].dir)
- setlocal modifiable
- normal! "_dap
- setlocal nomodifiable
- echo 'Reverted'
-endfunction
-
-function! s:snapshot(force, ...) abort
- call s:prepare()
- setf vim
- call append(0, ['" Generated by vim-plug',
- \ '" '.strftime("%c"),
- \ '" :source this file in vim to restore the snapshot',
- \ '" or execute: vim -S snapshot.vim',
- \ '', '', 'PlugUpdate!'])
- 1
- let anchor = line('$') - 3
- let names = sort(keys(filter(copy(g:plugs),
- \'has_key(v:val, "uri") && !has_key(v:val, "commit") && isdirectory(v:val.dir)')))
- for name in reverse(names)
- let sha = s:system_chomp('git rev-parse --short HEAD', g:plugs[name].dir)
- if !empty(sha)
- call append(anchor, printf("silent! let g:plugs['%s'].commit = '%s'", name, sha))
- redraw
- endif
- endfor
-
- if a:0 > 0
- let fn = expand(a:1)
- if filereadable(fn) && !(a:force || s:ask(a:1.' already exists. Overwrite?'))
- return
- endif
- call writefile(getline(1, '$'), fn)
- echo 'Saved as '.a:1
- silent execute 'e' s:esc(fn)
- setf vim
- endif
-endfunction
-
-function! s:split_rtp()
- return split(&rtp, '\\\@<!,')
-endfunction
-
-let s:first_rtp = s:escrtp(get(s:split_rtp(), 0, ''))
-let s:last_rtp = s:escrtp(get(s:split_rtp(), -1, ''))
-
-if exists('g:plugs')
- let g:plugs_order = get(g:, 'plugs_order', keys(g:plugs))
- call s:upgrade_specs()
- call s:define_commands()
-endif
-
-let &cpo = s:cpo_save
-unlet s:cpo_save
diff --git a/nvim/init.vim b/nvim/init.vim
index 2085c0d..6d617d9 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,26 +1,12 @@
-call plug#begin('~/.vim/plugged')
-Plug 'christoomey/vim-tmux-navigator'
-Plug 'jeffkreeftmeijer/neovim-sensible'
-Plug 'jeffkreeftmeijer/vim-dim'
-Plug 'jeffkreeftmeijer/vim-numbertoggle'
-Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
-Plug 'junegunn/fzf.vim'
-Plug 'junegunn/goyo.vim'
-Plug 'sheerun/vim-polyglot'
-Plug 'tpope/vim-commentary'
-Plug 'tpope/vim-fugitive'
-Plug 'w0rp/ale'
-call plug#end()
-
colors dim
" Enable mouse/trackpad scrolling
set mouse=a
" fzf.vim
nnoremap <silent> ,t :Files<CR>
nnoremap <silent> ,b :Buffers<CR>
nnoremap <silent> ,a :Ag<CR>
" ale
let g:ale_lint_on_text_changed = 'never'
|
jeffkreeftmeijer/dotfiles
|
042af3cfdd83bd10dd8e185e47684c0cdcaa1b54
|
Add Vim plugins as submodules in nvim/pack
|
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..8adb4e9
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,30 @@
+[submodule "nvim/pack/plugins/start/vim-tmux-navigator"]
+ path = nvim/pack/plugins/start/vim-tmux-navigator
+ url = [email protected]:christoomey/vim-tmux-navigator.git
+[submodule "nvim/pack/plugins/start/neovim-sensible"]
+ path = nvim/pack/plugins/start/neovim-sensible
+ url = [email protected]:jeffkreeftmeijer/neovim-sensible.git
+[submodule "nvim/pack/plugins/start/vim-dim"]
+ path = nvim/pack/plugins/start/vim-dim
+ url = [email protected]:jeffkreeftmeijer/vim-dim.git
+[submodule "nvim/pack/plugins/start/vim-numbertoggle"]
+ path = nvim/pack/plugins/start/vim-numbertoggle
+ url = [email protected]:jeffkreeftmeijer/vim-numbertoggle.git
+[submodule "nvim/pack/plugins/start/fzf.vim"]
+ path = nvim/pack/plugins/start/fzf.vim
+ url = [email protected]:junegunn/fzf.vim.git
+[submodule "nvim/pack/plugins/start/goyo.vim"]
+ path = nvim/pack/plugins/start/goyo.vim
+ url = [email protected]:junegunn/goyo.vim.git
+[submodule "nvim/pack/plugins/start/vim-polyglot"]
+ path = nvim/pack/plugins/start/vim-polyglot
+ url = [email protected]:sheerun/vim-polyglot.git
+[submodule "nvim/pack/plugins/start/vim-commentary"]
+ path = nvim/pack/plugins/start/vim-commentary
+ url = [email protected]:tpope/vim-commentary.git
+[submodule "nvim/pack/plugins/start/vim-fugitive"]
+ path = nvim/pack/plugins/start/vim-fugitive
+ url = [email protected]:tpope/vim-fugitive.git
+[submodule "nvim/pack/plugins/start/ale"]
+ path = nvim/pack/plugins/start/ale
+ url = [email protected]:w0rp/ale.git
diff --git a/nvim/pack/plugins/start/ale b/nvim/pack/plugins/start/ale
new file mode 160000
index 0000000..70fdeb7
--- /dev/null
+++ b/nvim/pack/plugins/start/ale
@@ -0,0 +1 @@
+Subproject commit 70fdeb7c228b512f042d8ffe11e9c5e1579bcb5f
diff --git a/nvim/pack/plugins/start/fzf.vim b/nvim/pack/plugins/start/fzf.vim
new file mode 160000
index 0000000..36f6e6b
--- /dev/null
+++ b/nvim/pack/plugins/start/fzf.vim
@@ -0,0 +1 @@
+Subproject commit 36f6e6b5b035bd8ca1dd45aff4b7e6da7ca890bb
diff --git a/nvim/pack/plugins/start/goyo.vim b/nvim/pack/plugins/start/goyo.vim
new file mode 160000
index 0000000..5b8bd03
--- /dev/null
+++ b/nvim/pack/plugins/start/goyo.vim
@@ -0,0 +1 @@
+Subproject commit 5b8bd0378758c1d9550d8429bef24b3d6d78b592
diff --git a/nvim/pack/plugins/start/neovim-sensible b/nvim/pack/plugins/start/neovim-sensible
new file mode 160000
index 0000000..41dd70b
--- /dev/null
+++ b/nvim/pack/plugins/start/neovim-sensible
@@ -0,0 +1 @@
+Subproject commit 41dd70be9a77598082f95d8541fcb5a8eb50d129
diff --git a/nvim/pack/plugins/start/vim-commentary b/nvim/pack/plugins/start/vim-commentary
new file mode 160000
index 0000000..be79030
--- /dev/null
+++ b/nvim/pack/plugins/start/vim-commentary
@@ -0,0 +1 @@
+Subproject commit be79030b3e8c0ee3c5f45b4333919e4830531e80
diff --git a/nvim/pack/plugins/start/vim-dim b/nvim/pack/plugins/start/vim-dim
new file mode 160000
index 0000000..6bfaf7d
--- /dev/null
+++ b/nvim/pack/plugins/start/vim-dim
@@ -0,0 +1 @@
+Subproject commit 6bfaf7db10dee1068c6b271423650c88707068b9
diff --git a/nvim/pack/plugins/start/vim-fugitive b/nvim/pack/plugins/start/vim-fugitive
new file mode 160000
index 0000000..8f60d1d
--- /dev/null
+++ b/nvim/pack/plugins/start/vim-fugitive
@@ -0,0 +1 @@
+Subproject commit 8f60d1d459362771cb68c0097565efdf52e62ec3
diff --git a/nvim/pack/plugins/start/vim-numbertoggle b/nvim/pack/plugins/start/vim-numbertoggle
new file mode 160000
index 0000000..22a9b7d
--- /dev/null
+++ b/nvim/pack/plugins/start/vim-numbertoggle
@@ -0,0 +1 @@
+Subproject commit 22a9b7db2162ca00d9266b4fd5d15b8e4a0de614
diff --git a/nvim/pack/plugins/start/vim-polyglot b/nvim/pack/plugins/start/vim-polyglot
new file mode 160000
index 0000000..9bfde75
--- /dev/null
+++ b/nvim/pack/plugins/start/vim-polyglot
@@ -0,0 +1 @@
+Subproject commit 9bfde7574aa89a91b80ed9c993fc000cfc11aae7
diff --git a/nvim/pack/plugins/start/vim-tmux-navigator b/nvim/pack/plugins/start/vim-tmux-navigator
new file mode 160000
index 0000000..d724094
--- /dev/null
+++ b/nvim/pack/plugins/start/vim-tmux-navigator
@@ -0,0 +1 @@
+Subproject commit d724094e7128acd7375cc758008f1e1688130877
|
jeffkreeftmeijer/dotfiles
|
cc0760c5827c21a4130cd0ffdd09d2f2453e5884
|
Add ale
|
diff --git a/nvim/init.vim b/nvim/init.vim
index f38bc3c..2085c0d 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,22 +1,26 @@
call plug#begin('~/.vim/plugged')
Plug 'christoomey/vim-tmux-navigator'
Plug 'jeffkreeftmeijer/neovim-sensible'
Plug 'jeffkreeftmeijer/vim-dim'
Plug 'jeffkreeftmeijer/vim-numbertoggle'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'junegunn/goyo.vim'
Plug 'sheerun/vim-polyglot'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
+Plug 'w0rp/ale'
call plug#end()
colors dim
" Enable mouse/trackpad scrolling
set mouse=a
" fzf.vim
nnoremap <silent> ,t :Files<CR>
nnoremap <silent> ,b :Buffers<CR>
nnoremap <silent> ,a :Ag<CR>
+
+" ale
+let g:ale_lint_on_text_changed = 'never'
|
jeffkreeftmeijer/dotfiles
|
7ef65917fbfdea4ba65eb51d89cc729453d6fcc1
|
Enable mouse/trackpad scrolling for tmux and vim
|
diff --git a/.tmux.conf b/.tmux.conf
index 18fe2b7..5cff0c4 100644
--- a/.tmux.conf
+++ b/.tmux.conf
@@ -1,31 +1,34 @@
# Use Ctrl-a instead of Ctrl-b as the tmux prefix
set-option -g prefix C-a
# Set the base index to 1 instead of 0 for both windows and panes.
set-option -g base-index 1
set-option -g pane-base-index 1
# Use vim keybindings in copy mode
setw -g mode-keys vi
# Setup 'v' to begin selection as in Vim
bind-key -t vi-copy v begin-selection
bind-key -t vi-copy y copy-pipe "reattach-to-user-namespace pbcopy"
# Update default binding of `Enter` to also use copy-pipe
unbind -t vi-copy Enter
bind-key -t vi-copy Enter copy-pipe "reattach-to-user-namespace pbcopy"
# Bind ']' to use pbpaste
bind ] run "reattach-to-user-namespace pbpaste | tmux load-buffer - && tmux paste-buffer"
# Open new windows and splits in the current path
bind-key c new-window -c "#{pane_current_path}"
bind-key % split-window -h -c "#{pane_current_path}"
bind-key '"' split-window -v -c "#{pane_current_path}"
+# Enable mouse/trackpad scrolling
+set -g mouse on
+
# List of plugins
set -g @plugin 'christoomey/vim-tmux-navigator'
set -g @plugin 'tmux-plugins/tmux-sensible'
set -g @plugin 'tmux-plugins/tpm'
run '~/.tmux/plugins/tpm/tpm'
diff --git a/nvim/init.vim b/nvim/init.vim
index 8fb6f89..f38bc3c 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,19 +1,22 @@
call plug#begin('~/.vim/plugged')
Plug 'christoomey/vim-tmux-navigator'
Plug 'jeffkreeftmeijer/neovim-sensible'
Plug 'jeffkreeftmeijer/vim-dim'
Plug 'jeffkreeftmeijer/vim-numbertoggle'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'junegunn/goyo.vim'
Plug 'sheerun/vim-polyglot'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
call plug#end()
colors dim
+" Enable mouse/trackpad scrolling
+set mouse=a
+
" fzf.vim
nnoremap <silent> ,t :Files<CR>
nnoremap <silent> ,b :Buffers<CR>
nnoremap <silent> ,a :Ag<CR>
|
jeffkreeftmeijer/dotfiles
|
138d2d200bcedc0097e28fea5af11f0c7cbd2e71
|
$ git config --global alias.git '!git'
|
diff --git a/.gitconfig b/.gitconfig
index eb3bdca..8c08f9c 100644
--- a/.gitconfig
+++ b/.gitconfig
@@ -1,5 +1,7 @@
[user]
name = Jeff Kreeftmeijer
email = [email protected]
[core]
excludesfile = ~/.config/.gitignore
+[alias]
+ git = !git
|
jeffkreeftmeijer/dotfiles
|
7d72d2bd2a9f3d2c8c054132cf36137f795fe48d
|
Check in .gitconfig
|
diff --git a/.gitconfig b/.gitconfig
new file mode 100644
index 0000000..eb3bdca
--- /dev/null
+++ b/.gitconfig
@@ -0,0 +1,5 @@
+[user]
+ name = Jeff Kreeftmeijer
+ email = [email protected]
+[core]
+ excludesfile = ~/.config/.gitignore
|
jeffkreeftmeijer/dotfiles
|
3837afa19095ea0b5ab8b30cd7c20d5106983bd5
|
Move tabs and list config to neovim-sensible
|
diff --git a/nvim/init.vim b/nvim/init.vim
index 85fab0d..8fb6f89 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,27 +1,19 @@
call plug#begin('~/.vim/plugged')
Plug 'christoomey/vim-tmux-navigator'
Plug 'jeffkreeftmeijer/neovim-sensible'
Plug 'jeffkreeftmeijer/vim-dim'
Plug 'jeffkreeftmeijer/vim-numbertoggle'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'junegunn/goyo.vim'
Plug 'sheerun/vim-polyglot'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
call plug#end()
colors dim
" fzf.vim
nnoremap <silent> ,t :Files<CR>
nnoremap <silent> ,b :Buffers<CR>
nnoremap <silent> ,a :Ag<CR>
-
-" tabs
-set expandtab
-set shiftwidth=2
-
-" list
-set list
-set listchars=tab:ââ,trail:·
|
jeffkreeftmeijer/dotfiles
|
7e18a92ced2342ca218d9094806f08b8db35cc65
|
Add vim-numbertoggle
|
diff --git a/nvim/init.vim b/nvim/init.vim
index 2f77ef1..85fab0d 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,26 +1,27 @@
call plug#begin('~/.vim/plugged')
Plug 'christoomey/vim-tmux-navigator'
Plug 'jeffkreeftmeijer/neovim-sensible'
Plug 'jeffkreeftmeijer/vim-dim'
+Plug 'jeffkreeftmeijer/vim-numbertoggle'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'junegunn/goyo.vim'
Plug 'sheerun/vim-polyglot'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
call plug#end()
colors dim
" fzf.vim
nnoremap <silent> ,t :Files<CR>
nnoremap <silent> ,b :Buffers<CR>
nnoremap <silent> ,a :Ag<CR>
" tabs
set expandtab
set shiftwidth=2
" list
set list
set listchars=tab:ââ,trail:·
|
jeffkreeftmeijer/dotfiles
|
d816b130a63aec778119cd5e5a252434cf5e07da
|
Add vim-polyglot, remove plugins for elixir, coffee, rust and liquid
|
diff --git a/nvim/init.vim b/nvim/init.vim
index d15f6b4..2f77ef1 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,29 +1,26 @@
call plug#begin('~/.vim/plugged')
Plug 'christoomey/vim-tmux-navigator'
-Plug 'elixir-lang/vim-elixir'
Plug 'jeffkreeftmeijer/neovim-sensible'
Plug 'jeffkreeftmeijer/vim-dim'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'junegunn/goyo.vim'
-Plug 'kchmck/vim-coffee-script'
-Plug 'rust-lang/rust.vim'
+Plug 'sheerun/vim-polyglot'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
-Plug 'tpope/vim-liquid'
call plug#end()
colors dim
" fzf.vim
nnoremap <silent> ,t :Files<CR>
nnoremap <silent> ,b :Buffers<CR>
nnoremap <silent> ,a :Ag<CR>
" tabs
set expandtab
set shiftwidth=2
" list
set list
set listchars=tab:ââ,trail:·
|
jeffkreeftmeijer/dotfiles
|
da5083ce88257cb4295ada1f88e2b1f02894984a
|
Use , instead of <leader> in init.vim
|
diff --git a/nvim/init.vim b/nvim/init.vim
index 21331a0..d15f6b4 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,29 +1,29 @@
call plug#begin('~/.vim/plugged')
Plug 'christoomey/vim-tmux-navigator'
Plug 'elixir-lang/vim-elixir'
Plug 'jeffkreeftmeijer/neovim-sensible'
Plug 'jeffkreeftmeijer/vim-dim'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'junegunn/goyo.vim'
Plug 'kchmck/vim-coffee-script'
Plug 'rust-lang/rust.vim'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-liquid'
call plug#end()
colors dim
" fzf.vim
-nnoremap <silent> <leader>t :Files<CR>
-nnoremap <silent> <leader>b :Buffers<CR>
-nnoremap <silent> <leader>a :Ag<CR>
+nnoremap <silent> ,t :Files<CR>
+nnoremap <silent> ,b :Buffers<CR>
+nnoremap <silent> ,a :Ag<CR>
" tabs
set expandtab
set shiftwidth=2
" list
set list
set listchars=tab:ââ,trail:·
|
jeffkreeftmeijer/dotfiles
|
f40c3a9f271fde23845f6f0dcc56fd8e89ae3cbc
|
vim: set tab with, show trailing spaces and tabs
|
diff --git a/nvim/init.vim b/nvim/init.vim
index 358d50c..21331a0 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,21 +1,29 @@
call plug#begin('~/.vim/plugged')
Plug 'christoomey/vim-tmux-navigator'
Plug 'elixir-lang/vim-elixir'
Plug 'jeffkreeftmeijer/neovim-sensible'
Plug 'jeffkreeftmeijer/vim-dim'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'junegunn/goyo.vim'
Plug 'kchmck/vim-coffee-script'
Plug 'rust-lang/rust.vim'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
Plug 'tpope/vim-liquid'
call plug#end()
colors dim
" fzf.vim
nnoremap <silent> <leader>t :Files<CR>
nnoremap <silent> <leader>b :Buffers<CR>
nnoremap <silent> <leader>a :Ag<CR>
+
+" tabs
+set expandtab
+set shiftwidth=2
+
+" list
+set list
+set listchars=tab:ââ,trail:·
|
jeffkreeftmeijer/dotfiles
|
937655a2d6aa6d190c3ccf7191535cb2fd264eba
|
Remove rbenv from .bash_profile
|
diff --git a/.bash_profile b/.bash_profile
index b13543d..72961f2 100644
--- a/.bash_profile
+++ b/.bash_profile
@@ -1,27 +1,24 @@
source ~/.config/bash/git-prompt.sh/git-prompt.sh
# PS1: "~/foo/bar/baz $ "
export PS1='\w $(__git_ps1 "(%s) ")$ '
# History control:
# - ignorespace: lines which begin with a space character are not saved
# - ignoredups: lines matching the previous history entry are not saved
# - erasedups: all previous lines matching the current line are removed before
# the new line is saved
export HISTCONTROL=ignorespace:ignoredups:erasedups
# Unlimited history
export HISTFILESIZE=
export HISTSIZE=
# Append to history instead of overwriting
shopt -s histappend
# Use nvim as $EDITOR
export EDITOR=nvim
# Colorize ls by default
alias ls='ls -G'
-
-# rbenv
-eval "$(rbenv init -)"
|
jeffkreeftmeijer/dotfiles
|
21b5d909fd270f182d1c3b84541f29e9d5806fb2
|
Add vim-liquid
|
diff --git a/nvim/init.vim b/nvim/init.vim
index bd324d7..358d50c 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,20 +1,21 @@
call plug#begin('~/.vim/plugged')
Plug 'christoomey/vim-tmux-navigator'
Plug 'elixir-lang/vim-elixir'
Plug 'jeffkreeftmeijer/neovim-sensible'
Plug 'jeffkreeftmeijer/vim-dim'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'junegunn/goyo.vim'
Plug 'kchmck/vim-coffee-script'
Plug 'rust-lang/rust.vim'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
+Plug 'tpope/vim-liquid'
call plug#end()
colors dim
" fzf.vim
nnoremap <silent> <leader>t :Files<CR>
nnoremap <silent> <leader>b :Buffers<CR>
nnoremap <silent> <leader>a :Ag<CR>
|
jeffkreeftmeijer/dotfiles
|
3cd83034af13df5e9d35e0b737b1c27fa22d1728
|
Add git-prompt.sh and set PS1
|
diff --git a/.bash_profile b/.bash_profile
index 09cd0d6..b13543d 100644
--- a/.bash_profile
+++ b/.bash_profile
@@ -1,25 +1,27 @@
+source ~/.config/bash/git-prompt.sh/git-prompt.sh
+
# PS1: "~/foo/bar/baz $ "
-export PS1="\w $ "
+export PS1='\w $(__git_ps1 "(%s) ")$ '
# History control:
# - ignorespace: lines which begin with a space character are not saved
# - ignoredups: lines matching the previous history entry are not saved
# - erasedups: all previous lines matching the current line are removed before
# the new line is saved
export HISTCONTROL=ignorespace:ignoredups:erasedups
# Unlimited history
export HISTFILESIZE=
export HISTSIZE=
# Append to history instead of overwriting
shopt -s histappend
# Use nvim as $EDITOR
export EDITOR=nvim
# Colorize ls by default
alias ls='ls -G'
# rbenv
eval "$(rbenv init -)"
diff --git a/bash/git-prompt.sh b/bash/git-prompt.sh
new file mode 160000
index 0000000..40febf9
--- /dev/null
+++ b/bash/git-prompt.sh
@@ -0,0 +1 @@
+Subproject commit 40febf97e56c18041d7323c528c0372f00c265b1
|
jeffkreeftmeijer/dotfiles
|
a8ba4e8cf470947562ecfea9e4c63feec4520dd5
|
Install vim-tmux-navigator
|
diff --git a/.tmux.conf b/.tmux.conf
index 869107d..18fe2b7 100644
--- a/.tmux.conf
+++ b/.tmux.conf
@@ -1,30 +1,31 @@
# Use Ctrl-a instead of Ctrl-b as the tmux prefix
set-option -g prefix C-a
# Set the base index to 1 instead of 0 for both windows and panes.
set-option -g base-index 1
set-option -g pane-base-index 1
# Use vim keybindings in copy mode
setw -g mode-keys vi
# Setup 'v' to begin selection as in Vim
bind-key -t vi-copy v begin-selection
bind-key -t vi-copy y copy-pipe "reattach-to-user-namespace pbcopy"
# Update default binding of `Enter` to also use copy-pipe
unbind -t vi-copy Enter
bind-key -t vi-copy Enter copy-pipe "reattach-to-user-namespace pbcopy"
# Bind ']' to use pbpaste
bind ] run "reattach-to-user-namespace pbpaste | tmux load-buffer - && tmux paste-buffer"
# Open new windows and splits in the current path
bind-key c new-window -c "#{pane_current_path}"
bind-key % split-window -h -c "#{pane_current_path}"
bind-key '"' split-window -v -c "#{pane_current_path}"
# List of plugins
-set -g @plugin 'tmux-plugins/tpm'
+set -g @plugin 'christoomey/vim-tmux-navigator'
set -g @plugin 'tmux-plugins/tmux-sensible'
+set -g @plugin 'tmux-plugins/tpm'
run '~/.tmux/plugins/tpm/tpm'
diff --git a/.tmux/plugins/vim-tmux-navigator b/.tmux/plugins/vim-tmux-navigator
new file mode 160000
index 0000000..e79d4c0
--- /dev/null
+++ b/.tmux/plugins/vim-tmux-navigator
@@ -0,0 +1 @@
+Subproject commit e79d4c0c24c43d3ada283b1f5a1b8fa6cf820a70
diff --git a/nvim/init.vim b/nvim/init.vim
index c85104d..88d51e4 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,19 +1,22 @@
call plug#begin('~/.vim/plugged')
+Plug 'christoomey/vim-tmux-navigator'
Plug 'elixir-lang/vim-elixir'
Plug 'jeffkreeftmeijer/neovim-sensible'
Plug 'jeffkreeftmeijer/vim-dim'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'junegunn/goyo.vim'
Plug 'kchmck/vim-coffee-script'
Plug 'rust-lang/rust.vim'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
call plug#end()
colors dim
" fzf.vim
nnoremap <silent> <leader>t :Files<CR>
nnoremap <silent> <leader>b :Buffers<CR>
nnoremap <silent> <leader>a :Ag<CR>
+
+nnoremap <silent> <BS> :TmuxNavigateLeft<cr>
|
jeffkreeftmeijer/dotfiles
|
a193ee8b2206d78a053bb74f43b9fec546cb339b
|
tmux: install tmux-sensible, clean up duplicate config
|
diff --git a/.tmux.conf b/.tmux.conf
index 68bef79..869107d 100644
--- a/.tmux.conf
+++ b/.tmux.conf
@@ -1,38 +1,30 @@
# Use Ctrl-a instead of Ctrl-b as the tmux prefix
set-option -g prefix C-a
# Set the base index to 1 instead of 0 for both windows and panes.
set-option -g base-index 1
set-option -g pane-base-index 1
-# Set the escape-time to 1 to remove the delay when sending commands.
-set-option -gs escape-time 1
-
-# Use reattach to user namespace (for clipboard support in Neovim)
-set -g default-command "reattach-to-user-namespace -l ${SHELL}"
-
-# 256 colors in tmux
-set -g default-terminal "screen-256color"
-
# Use vim keybindings in copy mode
setw -g mode-keys vi
# Setup 'v' to begin selection as in Vim
bind-key -t vi-copy v begin-selection
bind-key -t vi-copy y copy-pipe "reattach-to-user-namespace pbcopy"
# Update default binding of `Enter` to also use copy-pipe
unbind -t vi-copy Enter
bind-key -t vi-copy Enter copy-pipe "reattach-to-user-namespace pbcopy"
# Bind ']' to use pbpaste
bind ] run "reattach-to-user-namespace pbpaste | tmux load-buffer - && tmux paste-buffer"
# Open new windows and splits in the current path
bind-key c new-window -c "#{pane_current_path}"
bind-key % split-window -h -c "#{pane_current_path}"
bind-key '"' split-window -v -c "#{pane_current_path}"
# List of plugins
set -g @plugin 'tmux-plugins/tpm'
+set -g @plugin 'tmux-plugins/tmux-sensible'
run '~/.tmux/plugins/tpm/tpm'
diff --git a/.tmux/plugins/tmux-sensible b/.tmux/plugins/tmux-sensible
new file mode 160000
index 0000000..526110e
--- /dev/null
+++ b/.tmux/plugins/tmux-sensible
@@ -0,0 +1 @@
+Subproject commit 526110eb9b60825d3276afba97ffa4cedb4b0ab9
|
jeffkreeftmeijer/dotfiles
|
2cd92a4b0d4f6eb13abde803cf6b3d58ab4def92
|
tmux: Add TPM
|
diff --git a/.tmux.conf b/.tmux.conf
index cde5671..68bef79 100644
--- a/.tmux.conf
+++ b/.tmux.conf
@@ -1,34 +1,38 @@
# Use Ctrl-a instead of Ctrl-b as the tmux prefix
set-option -g prefix C-a
# Set the base index to 1 instead of 0 for both windows and panes.
set-option -g base-index 1
set-option -g pane-base-index 1
# Set the escape-time to 1 to remove the delay when sending commands.
set-option -gs escape-time 1
# Use reattach to user namespace (for clipboard support in Neovim)
set -g default-command "reattach-to-user-namespace -l ${SHELL}"
# 256 colors in tmux
set -g default-terminal "screen-256color"
# Use vim keybindings in copy mode
setw -g mode-keys vi
# Setup 'v' to begin selection as in Vim
bind-key -t vi-copy v begin-selection
bind-key -t vi-copy y copy-pipe "reattach-to-user-namespace pbcopy"
# Update default binding of `Enter` to also use copy-pipe
unbind -t vi-copy Enter
bind-key -t vi-copy Enter copy-pipe "reattach-to-user-namespace pbcopy"
# Bind ']' to use pbpaste
bind ] run "reattach-to-user-namespace pbpaste | tmux load-buffer - && tmux paste-buffer"
# Open new windows and splits in the current path
bind-key c new-window -c "#{pane_current_path}"
bind-key % split-window -h -c "#{pane_current_path}"
bind-key '"' split-window -v -c "#{pane_current_path}"
+
+# List of plugins
+set -g @plugin 'tmux-plugins/tpm'
+run '~/.tmux/plugins/tpm/tpm'
diff --git a/.tmux/plugins/tpm b/.tmux/plugins/tpm
new file mode 160000
index 0000000..0ea31ae
--- /dev/null
+++ b/.tmux/plugins/tpm
@@ -0,0 +1 @@
+Subproject commit 0ea31ae2d624413719e97dc7e138ed6cf749c7d2
|
jeffkreeftmeijer/dotfiles
|
183f6e35c4d01fe013e17ccf3c42e143b44a85db
|
tmux: Open new windows and splits in the current path
|
diff --git a/.tmux.conf b/.tmux.conf
index 2fa89dc..cde5671 100644
--- a/.tmux.conf
+++ b/.tmux.conf
@@ -1,29 +1,34 @@
# Use Ctrl-a instead of Ctrl-b as the tmux prefix
set-option -g prefix C-a
# Set the base index to 1 instead of 0 for both windows and panes.
set-option -g base-index 1
set-option -g pane-base-index 1
# Set the escape-time to 1 to remove the delay when sending commands.
set-option -gs escape-time 1
# Use reattach to user namespace (for clipboard support in Neovim)
set -g default-command "reattach-to-user-namespace -l ${SHELL}"
# 256 colors in tmux
set -g default-terminal "screen-256color"
# Use vim keybindings in copy mode
setw -g mode-keys vi
# Setup 'v' to begin selection as in Vim
bind-key -t vi-copy v begin-selection
bind-key -t vi-copy y copy-pipe "reattach-to-user-namespace pbcopy"
# Update default binding of `Enter` to also use copy-pipe
unbind -t vi-copy Enter
bind-key -t vi-copy Enter copy-pipe "reattach-to-user-namespace pbcopy"
# Bind ']' to use pbpaste
bind ] run "reattach-to-user-namespace pbpaste | tmux load-buffer - && tmux paste-buffer"
+
+# Open new windows and splits in the current path
+bind-key c new-window -c "#{pane_current_path}"
+bind-key % split-window -h -c "#{pane_current_path}"
+bind-key '"' split-window -v -c "#{pane_current_path}"
|
jeffkreeftmeijer/dotfiles
|
934db1d9d89e88ed749f3799c25422e316b5ce7a
|
Use the system paste buffer in tmux
|
diff --git a/.tmux.conf b/.tmux.conf
index 87483d5..2fa89dc 100644
--- a/.tmux.conf
+++ b/.tmux.conf
@@ -1,15 +1,29 @@
# Use Ctrl-a instead of Ctrl-b as the tmux prefix
set-option -g prefix C-a
# Set the base index to 1 instead of 0 for both windows and panes.
set-option -g base-index 1
set-option -g pane-base-index 1
# Set the escape-time to 1 to remove the delay when sending commands.
set-option -gs escape-time 1
# Use reattach to user namespace (for clipboard support in Neovim)
set -g default-command "reattach-to-user-namespace -l ${SHELL}"
# 256 colors in tmux
set -g default-terminal "screen-256color"
+
+# Use vim keybindings in copy mode
+setw -g mode-keys vi
+
+# Setup 'v' to begin selection as in Vim
+bind-key -t vi-copy v begin-selection
+bind-key -t vi-copy y copy-pipe "reattach-to-user-namespace pbcopy"
+
+# Update default binding of `Enter` to also use copy-pipe
+unbind -t vi-copy Enter
+bind-key -t vi-copy Enter copy-pipe "reattach-to-user-namespace pbcopy"
+
+# Bind ']' to use pbpaste
+bind ] run "reattach-to-user-namespace pbpaste | tmux load-buffer - && tmux paste-buffer"
|
jeffkreeftmeijer/dotfiles
|
50d97291fb9f817f2911d11fe98ab1f43c658f81
|
Use 256 colors in tmux
|
diff --git a/.tmux.conf b/.tmux.conf
index de52981..87483d5 100644
--- a/.tmux.conf
+++ b/.tmux.conf
@@ -1,12 +1,15 @@
# Use Ctrl-a instead of Ctrl-b as the tmux prefix
set-option -g prefix C-a
# Set the base index to 1 instead of 0 for both windows and panes.
set-option -g base-index 1
set-option -g pane-base-index 1
# Set the escape-time to 1 to remove the delay when sending commands.
set-option -gs escape-time 1
# Use reattach to user namespace (for clipboard support in Neovim)
set -g default-command "reattach-to-user-namespace -l ${SHELL}"
+
+# 256 colors in tmux
+set -g default-terminal "screen-256color"
|
jeffkreeftmeijer/dotfiles
|
7f14226fddeb68430070a541003f72f5136d9c47
|
Add shortcuts for fzf.vim
|
diff --git a/nvim/init.vim b/nvim/init.vim
index c3c8938..c85104d 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,14 +1,19 @@
call plug#begin('~/.vim/plugged')
Plug 'elixir-lang/vim-elixir'
Plug 'jeffkreeftmeijer/neovim-sensible'
Plug 'jeffkreeftmeijer/vim-dim'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'junegunn/goyo.vim'
Plug 'kchmck/vim-coffee-script'
Plug 'rust-lang/rust.vim'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
call plug#end()
colors dim
+
+" fzf.vim
+nnoremap <silent> <leader>t :Files<CR>
+nnoremap <silent> <leader>b :Buffers<CR>
+nnoremap <silent> <leader>a :Ag<CR>
|
jeffkreeftmeijer/dotfiles
|
0b86e06f2d3993e7e00190fd1ece2b7f558718b2
|
set -g default-command "reattach-to-user-namespace -l ${SHELL}"
|
diff --git a/.tmux.conf b/.tmux.conf
index 7300bc0..de52981 100644
--- a/.tmux.conf
+++ b/.tmux.conf
@@ -1,9 +1,12 @@
# Use Ctrl-a instead of Ctrl-b as the tmux prefix
set-option -g prefix C-a
# Set the base index to 1 instead of 0 for both windows and panes.
set-option -g base-index 1
set-option -g pane-base-index 1
# Set the escape-time to 1 to remove the delay when sending commands.
set-option -gs escape-time 1
+
+# Use reattach to user namespace (for clipboard support in Neovim)
+set -g default-command "reattach-to-user-namespace -l ${SHELL}"
diff --git a/bin/brew.sh b/bin/brew.sh
index 57b02df..8ebc0c6 100644
--- a/bin/brew.sh
+++ b/bin/brew.sh
@@ -1,18 +1,19 @@
brew install erlang elixir rbenv \
tmux neovim/neovim/neovim ag jpegoptim postgresql pow \
+ reattach-to-user-namespace \
homebrew/versions/mongodb30 redis chromedriver
# Start Postgres, Redis and Chromedriver
brew services start postgresql
brew services start redis
brew services start chromedriver
brew services start homebrew/versions/mongodb30
# Pow
mkdir -p ~/Library/Application\ Support/Pow/Hosts
ln -s ~/Library/Application\ Support/Pow/Hosts ~/.pow
sudo pow --install-system
pow --install-local
sudo launchctl load -w /Library/LaunchDaemons/cx.pow.firewall.plist
launchctl load -w ~/Library/LaunchAgents/cx.pow.powd.plist
|
jeffkreeftmeijer/dotfiles
|
0f155c7722c271818d3a9745c20ef4b662ca367e
|
Add elixir-lang/vim-elixir to init.vim
|
diff --git a/nvim/init.vim b/nvim/init.vim
index 2df75f7..c3c8938 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,13 +1,14 @@
call plug#begin('~/.vim/plugged')
+Plug 'elixir-lang/vim-elixir'
Plug 'jeffkreeftmeijer/neovim-sensible'
Plug 'jeffkreeftmeijer/vim-dim'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'junegunn/goyo.vim'
Plug 'kchmck/vim-coffee-script'
Plug 'rust-lang/rust.vim'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
call plug#end()
colors dim
|
jeffkreeftmeijer/dotfiles
|
912dfba0390c612da22b839ef5378928ea4e1d7e
|
Add Skype and Screenhero to cask.sh
|
diff --git a/bin/cask.sh b/bin/cask.sh
index c55307c..e8c7220 100644
--- a/bin/cask.sh
+++ b/bin/cask.sh
@@ -1,2 +1,2 @@
brew cask install whatsapp seil wacom-bamboo-tablet \
- slack tunnelblick google-chrome
+ slack tunnelblick google-chrome skype screenhero
|
jeffkreeftmeijer/dotfiles
|
c4bba7b95fd442207f29e27ebcd74ec90a96dc1b
|
Add rust.vim
|
diff --git a/nvim/init.vim b/nvim/init.vim
index f90e75b..2df75f7 100644
--- a/nvim/init.vim
+++ b/nvim/init.vim
@@ -1,12 +1,13 @@
call plug#begin('~/.vim/plugged')
Plug 'jeffkreeftmeijer/neovim-sensible'
Plug 'jeffkreeftmeijer/vim-dim'
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
Plug 'junegunn/fzf.vim'
Plug 'junegunn/goyo.vim'
Plug 'kchmck/vim-coffee-script'
+Plug 'rust-lang/rust.vim'
Plug 'tpope/vim-commentary'
Plug 'tpope/vim-fugitive'
call plug#end()
colors dim
|
jeffkreeftmeijer/dotfiles
|
423e539da33ae7a42fa7a82a30100cc2d86b45bc
|
Add vim-fugitive
|
diff --git a/.bash_profile b/.bash_profile
new file mode 100644
index 0000000..09cd0d6
--- /dev/null
+++ b/.bash_profile
@@ -0,0 +1,25 @@
+# PS1: "~/foo/bar/baz $ "
+export PS1="\w $ "
+
+# History control:
+# - ignorespace: lines which begin with a space character are not saved
+# - ignoredups: lines matching the previous history entry are not saved
+# - erasedups: all previous lines matching the current line are removed before
+# the new line is saved
+export HISTCONTROL=ignorespace:ignoredups:erasedups
+
+# Unlimited history
+export HISTFILESIZE=
+export HISTSIZE=
+
+# Append to history instead of overwriting
+shopt -s histappend
+
+# Use nvim as $EDITOR
+export EDITOR=nvim
+
+# Colorize ls by default
+alias ls='ls -G'
+
+# rbenv
+eval "$(rbenv init -)"
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..aa82804
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+.DS_Store
+.netrwhist
diff --git a/.inputrc b/.inputrc
new file mode 100644
index 0000000..8638ed5
--- /dev/null
+++ b/.inputrc
@@ -0,0 +1,2 @@
+"\e[A": history-search-backward
+"\e[B": history-search-forward
diff --git a/.tmux.conf b/.tmux.conf
new file mode 100644
index 0000000..7300bc0
--- /dev/null
+++ b/.tmux.conf
@@ -0,0 +1,9 @@
+# Use Ctrl-a instead of Ctrl-b as the tmux prefix
+set-option -g prefix C-a
+
+# Set the base index to 1 instead of 0 for both windows and panes.
+set-option -g base-index 1
+set-option -g pane-base-index 1
+
+# Set the escape-time to 1 to remove the delay when sending commands.
+set-option -gs escape-time 1
diff --git a/bin/.DS_Store b/bin/.DS_Store
new file mode 100644
index 0000000..cac4189
Binary files /dev/null and b/bin/.DS_Store differ
diff --git a/bin/brew.sh b/bin/brew.sh
new file mode 100644
index 0000000..57b02df
--- /dev/null
+++ b/bin/brew.sh
@@ -0,0 +1,18 @@
+brew install erlang elixir rbenv \
+ tmux neovim/neovim/neovim ag jpegoptim postgresql pow \
+ homebrew/versions/mongodb30 redis chromedriver
+
+# Start Postgres, Redis and Chromedriver
+brew services start postgresql
+brew services start redis
+brew services start chromedriver
+brew services start homebrew/versions/mongodb30
+
+# Pow
+mkdir -p ~/Library/Application\ Support/Pow/Hosts
+ln -s ~/Library/Application\ Support/Pow/Hosts ~/.pow
+sudo pow --install-system
+pow --install-local
+
+sudo launchctl load -w /Library/LaunchDaemons/cx.pow.firewall.plist
+launchctl load -w ~/Library/LaunchAgents/cx.pow.powd.plist
diff --git a/bin/cask.sh b/bin/cask.sh
new file mode 100644
index 0000000..c55307c
--- /dev/null
+++ b/bin/cask.sh
@@ -0,0 +1,2 @@
+brew cask install whatsapp seil wacom-bamboo-tablet \
+ slack tunnelblick google-chrome
diff --git a/bin/config.sh b/bin/config.sh
new file mode 100644
index 0000000..a4ec2da
--- /dev/null
+++ b/bin/config.sh
@@ -0,0 +1,38 @@
+# Faster (initial) key repeat
+defaults write -g InitialKeyRepeat -int 15 # 250ms
+defaults write -g KeyRepeat -int 2 #33ms
+
+# Remove all apps from the dock
+defaults write com.apple.dock persistent-apps -array
+
+# Automatically hide the dock
+defaults write com.apple.dock autohide -bool true
+
+# Remove Dock hide delay
+defaults write com.apple.dock autohide-delay -float 0
+defaults write com.apple.dock autohide-time-modifier -float 0
+
+# Hide icons from Desktop
+defaults write com.apple.finder CreateDesktop -bool false
+
+# Show hidden files in Finder
+defaults write com.apple.finder AppleShowAllFiles -bool YES
+
+# Tap to click
+defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad Clicking -bool true
+
+# Click trackpad corner to emulate right click
+defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadCornerSecondaryClick -bool true
+
+# Tap with two fingers to emulate right click
+defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad TrackpadRightClick -bool true
+
+# Remap caps lock to escape with Seil
+/Applications/Seil.app/Contents/Library/bin/seil set enable_capslock 1
+/Applications/Seil.app/Contents/Library/bin/seil set keycode_capslock 53
+
+# Enable the Develop menu and the Web Inspector in Safari
+defaults write com.apple.Safari IncludeDevelopMenu -bool true
+
+# Restart the Dock and Finder and quit Safari
+killall Dock Finder Safari
diff --git a/bin/jeff.sh b/bin/jeff.sh
new file mode 100644
index 0000000..6aa8c42
--- /dev/null
+++ b/bin/jeff.sh
@@ -0,0 +1,2 @@
+git config --global user.name "Jeff Kreeftmeijer"
+git config --global user.email [email protected]
diff --git a/bin/setup.sh b/bin/setup.sh
new file mode 100644
index 0000000..cb14a77
--- /dev/null
+++ b/bin/setup.sh
@@ -0,0 +1,6 @@
+# Homebrew
+/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
+
+# appsignal.terminal
+curl -OO https://gist.githubusercontent.com/jeffkreeftmeijer/5a9bb873233b1110eed9e8cd62591a85/raw/appsignal-{light,dark}.terminal
+open appsignal-*.terminal
diff --git a/nvim/autoload/plug.vim b/nvim/autoload/plug.vim
new file mode 100644
index 0000000..b0f5bc2
--- /dev/null
+++ b/nvim/autoload/plug.vim
@@ -0,0 +1,2414 @@
+" vim-plug: Vim plugin manager
+" ============================
+"
+" Download plug.vim and put it in ~/.vim/autoload
+"
+" curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
+" https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
+"
+" Edit your .vimrc
+"
+" call plug#begin('~/.vim/plugged')
+"
+" " Make sure you use single quotes
+"
+" " Shorthand notation; fetches https://github.com/junegunn/vim-easy-align
+" Plug 'junegunn/vim-easy-align'
+"
+" " Any valid git URL is allowed
+" Plug 'https://github.com/junegunn/vim-github-dashboard.git'
+"
+" " Group dependencies, vim-snippets depends on ultisnips
+" Plug 'SirVer/ultisnips' | Plug 'honza/vim-snippets'
+"
+" " On-demand loading
+" Plug 'scrooloose/nerdtree', { 'on': 'NERDTreeToggle' }
+" Plug 'tpope/vim-fireplace', { 'for': 'clojure' }
+"
+" " Using a non-master branch
+" Plug 'rdnetto/YCM-Generator', { 'branch': 'stable' }
+"
+" " Using a tagged release; wildcard allowed (requires git 1.9.2 or above)
+" Plug 'fatih/vim-go', { 'tag': '*' }
+"
+" " Plugin options
+" Plug 'nsf/gocode', { 'tag': 'v.20150303', 'rtp': 'vim' }
+"
+" " Plugin outside ~/.vim/plugged with post-update hook
+" Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
+"
+" " Unmanaged plugin (manually installed and updated)
+" Plug '~/my-prototype-plugin'
+"
+" " Add plugins to &runtimepath
+" call plug#end()
+"
+" Then reload .vimrc and :PlugInstall to install plugins.
+"
+" Plug options:
+"
+"| Option | Description |
+"| ----------------------- | ------------------------------------------------ |
+"| `branch`/`tag`/`commit` | Branch/tag/commit of the repository to use |
+"| `rtp` | Subdirectory that contains Vim plugin |
+"| `dir` | Custom directory for the plugin |
+"| `as` | Use different name for the plugin |
+"| `do` | Post-update hook (string or funcref) |
+"| `on` | On-demand loading: Commands or `<Plug>`-mappings |
+"| `for` | On-demand loading: File types |
+"| `frozen` | Do not update unless explicitly specified |
+"
+" More information: https://github.com/junegunn/vim-plug
+"
+"
+" Copyright (c) 2016 Junegunn Choi
+"
+" MIT License
+"
+" Permission is hereby granted, free of charge, to any person obtaining
+" a copy of this software and associated documentation files (the
+" "Software"), to deal in the Software without restriction, including
+" without limitation the rights to use, copy, modify, merge, publish,
+" distribute, sublicense, and/or sell copies of the Software, and to
+" permit persons to whom the Software is furnished to do so, subject to
+" the following conditions:
+"
+" The above copyright notice and this permission notice shall be
+" included in all copies or substantial portions of the Software.
+"
+" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+" NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+" LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+" OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+" WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+if exists('g:loaded_plug')
+ finish
+endif
+let g:loaded_plug = 1
+
+let s:cpo_save = &cpo
+set cpo&vim
+
+let s:plug_src = 'https://github.com/junegunn/vim-plug.git'
+let s:plug_tab = get(s:, 'plug_tab', -1)
+let s:plug_buf = get(s:, 'plug_buf', -1)
+let s:mac_gui = has('gui_macvim') && has('gui_running')
+let s:is_win = has('win32') || has('win64')
+let s:nvim = has('nvim') && exists('*jobwait') && !s:is_win
+let s:vim8 = has('patch-8.0.0039') && exists('*job_start')
+let s:me = resolve(expand('<sfile>:p'))
+let s:base_spec = { 'branch': 'master', 'frozen': 0 }
+let s:TYPE = {
+\ 'string': type(''),
+\ 'list': type([]),
+\ 'dict': type({}),
+\ 'funcref': type(function('call'))
+\ }
+let s:loaded = get(s:, 'loaded', {})
+let s:triggers = get(s:, 'triggers', {})
+
+function! plug#begin(...)
+ if a:0 > 0
+ let s:plug_home_org = a:1
+ let home = s:path(fnamemodify(expand(a:1), ':p'))
+ elseif exists('g:plug_home')
+ let home = s:path(g:plug_home)
+ elseif !empty(&rtp)
+ let home = s:path(split(&rtp, ',')[0]) . '/plugged'
+ else
+ return s:err('Unable to determine plug home. Try calling plug#begin() with a path argument.')
+ endif
+
+ let g:plug_home = home
+ let g:plugs = {}
+ let g:plugs_order = []
+ let s:triggers = {}
+
+ call s:define_commands()
+ return 1
+endfunction
+
+function! s:define_commands()
+ command! -nargs=+ -bar Plug call plug#(<args>)
+ if !executable('git')
+ return s:err('`git` executable not found. Most commands will not be available. To suppress this message, prepend `silent!` to `call plug#begin(...)`.')
+ endif
+ command! -nargs=* -bar -bang -complete=customlist,s:names PlugInstall call s:install(<bang>0, [<f-args>])
+ command! -nargs=* -bar -bang -complete=customlist,s:names PlugUpdate call s:update(<bang>0, [<f-args>])
+ command! -nargs=0 -bar -bang PlugClean call s:clean(<bang>0)
+ command! -nargs=0 -bar PlugUpgrade if s:upgrade() | execute 'source' s:esc(s:me) | endif
+ command! -nargs=0 -bar PlugStatus call s:status()
+ command! -nargs=0 -bar PlugDiff call s:diff()
+ command! -nargs=? -bar -bang -complete=file PlugSnapshot call s:snapshot(<bang>0, <f-args>)
+endfunction
+
+function! s:to_a(v)
+ return type(a:v) == s:TYPE.list ? a:v : [a:v]
+endfunction
+
+function! s:to_s(v)
+ return type(a:v) == s:TYPE.string ? a:v : join(a:v, "\n") . "\n"
+endfunction
+
+function! s:glob(from, pattern)
+ return s:lines(globpath(a:from, a:pattern))
+endfunction
+
+function! s:source(from, ...)
+ let found = 0
+ for pattern in a:000
+ for vim in s:glob(a:from, pattern)
+ execute 'source' s:esc(vim)
+ let found = 1
+ endfor
+ endfor
+ return found
+endfunction
+
+function! s:assoc(dict, key, val)
+ let a:dict[a:key] = add(get(a:dict, a:key, []), a:val)
+endfunction
+
+function! s:ask(message, ...)
+ call inputsave()
+ echohl WarningMsg
+ let answer = input(a:message.(a:0 ? ' (y/N/a) ' : ' (y/N) '))
+ echohl None
+ call inputrestore()
+ echo "\r"
+ return (a:0 && answer =~? '^a') ? 2 : (answer =~? '^y') ? 1 : 0
+endfunction
+
+function! s:ask_no_interrupt(...)
+ try
+ return call('s:ask', a:000)
+ catch
+ return 0
+ endtry
+endfunction
+
+function! plug#end()
+ if !exists('g:plugs')
+ return s:err('Call plug#begin() first')
+ endif
+
+ if exists('#PlugLOD')
+ augroup PlugLOD
+ autocmd!
+ augroup END
+ augroup! PlugLOD
+ endif
+ let lod = { 'ft': {}, 'map': {}, 'cmd': {} }
+
+ if exists('g:did_load_filetypes')
+ filetype off
+ endif
+ for name in g:plugs_order
+ if !has_key(g:plugs, name)
+ continue
+ endif
+ let plug = g:plugs[name]
+ if get(s:loaded, name, 0) || !has_key(plug, 'on') && !has_key(plug, 'for')
+ let s:loaded[name] = 1
+ continue
+ endif
+
+ if has_key(plug, 'on')
+ let s:triggers[name] = { 'map': [], 'cmd': [] }
+ for cmd in s:to_a(plug.on)
+ if cmd =~? '^<Plug>.\+'
+ if empty(mapcheck(cmd)) && empty(mapcheck(cmd, 'i'))
+ call s:assoc(lod.map, cmd, name)
+ endif
+ call add(s:triggers[name].map, cmd)
+ elseif cmd =~# '^[A-Z]'
+ if exists(':'.cmd) != 2
+ call s:assoc(lod.cmd, cmd, name)
+ endif
+ call add(s:triggers[name].cmd, cmd)
+ else
+ call s:err('Invalid `on` option: '.cmd.
+ \ '. Should start with an uppercase letter or `<Plug>`.')
+ endif
+ endfor
+ endif
+
+ if has_key(plug, 'for')
+ let types = s:to_a(plug.for)
+ if !empty(types)
+ augroup filetypedetect
+ call s:source(s:rtp(plug), 'ftdetect/**/*.vim', 'after/ftdetect/**/*.vim')
+ augroup END
+ endif
+ for type in types
+ call s:assoc(lod.ft, type, name)
+ endfor
+ endif
+ endfor
+
+ for [cmd, names] in items(lod.cmd)
+ execute printf(
+ \ 'command! -nargs=* -range -bang -complete=file %s call s:lod_cmd(%s, "<bang>", <line1>, <line2>, <q-args>, %s)',
+ \ cmd, string(cmd), string(names))
+ endfor
+
+ for [map, names] in items(lod.map)
+ for [mode, map_prefix, key_prefix] in
+ \ [['i', '<C-O>', ''], ['n', '', ''], ['v', '', 'gv'], ['o', '', '']]
+ execute printf(
+ \ '%snoremap <silent> %s %s:<C-U>call <SID>lod_map(%s, %s, %s, "%s")<CR>',
+ \ mode, map, map_prefix, string(map), string(names), mode != 'i', key_prefix)
+ endfor
+ endfor
+
+ for [ft, names] in items(lod.ft)
+ augroup PlugLOD
+ execute printf('autocmd FileType %s call <SID>lod_ft(%s, %s)',
+ \ ft, string(ft), string(names))
+ augroup END
+ endfor
+
+ call s:reorg_rtp()
+ filetype plugin indent on
+ if has('vim_starting')
+ if has('syntax') && !exists('g:syntax_on')
+ syntax enable
+ end
+ else
+ call s:reload_plugins()
+ endif
+endfunction
+
+function! s:loaded_names()
+ return filter(copy(g:plugs_order), 'get(s:loaded, v:val, 0)')
+endfunction
+
+function! s:load_plugin(spec)
+ call s:source(s:rtp(a:spec), 'plugin/**/*.vim', 'after/plugin/**/*.vim')
+endfunction
+
+function! s:reload_plugins()
+ for name in s:loaded_names()
+ call s:load_plugin(g:plugs[name])
+ endfor
+endfunction
+
+function! s:trim(str)
+ return substitute(a:str, '[\/]\+$', '', '')
+endfunction
+
+function! s:version_requirement(val, min)
+ for idx in range(0, len(a:min) - 1)
+ let v = get(a:val, idx, 0)
+ if v < a:min[idx] | return 0
+ elseif v > a:min[idx] | return 1
+ endif
+ endfor
+ return 1
+endfunction
+
+function! s:git_version_requirement(...)
+ if !exists('s:git_version')
+ let s:git_version = map(split(split(s:system('git --version'))[2], '\.'), 'str2nr(v:val)')
+ endif
+ return s:version_requirement(s:git_version, a:000)
+endfunction
+
+function! s:progress_opt(base)
+ return a:base && !s:is_win &&
+ \ s:git_version_requirement(1, 7, 1) ? '--progress' : ''
+endfunction
+
+if s:is_win
+ function! s:rtp(spec)
+ return s:path(a:spec.dir . get(a:spec, 'rtp', ''))
+ endfunction
+
+ function! s:path(path)
+ return s:trim(substitute(a:path, '/', '\', 'g'))
+ endfunction
+
+ function! s:dirpath(path)
+ return s:path(a:path) . '\'
+ endfunction
+
+ function! s:is_local_plug(repo)
+ return a:repo =~? '^[a-z]:\|^[%~]'
+ endfunction
+else
+ function! s:rtp(spec)
+ return s:dirpath(a:spec.dir . get(a:spec, 'rtp', ''))
+ endfunction
+
+ function! s:path(path)
+ return s:trim(a:path)
+ endfunction
+
+ function! s:dirpath(path)
+ return substitute(a:path, '[/\\]*$', '/', '')
+ endfunction
+
+ function! s:is_local_plug(repo)
+ return a:repo[0] =~ '[/$~]'
+ endfunction
+endif
+
+function! s:err(msg)
+ echohl ErrorMsg
+ echom '[vim-plug] '.a:msg
+ echohl None
+endfunction
+
+function! s:warn(cmd, msg)
+ echohl WarningMsg
+ execute a:cmd 'a:msg'
+ echohl None
+endfunction
+
+function! s:esc(path)
+ return escape(a:path, ' ')
+endfunction
+
+function! s:escrtp(path)
+ return escape(a:path, ' ,')
+endfunction
+
+function! s:remove_rtp()
+ for name in s:loaded_names()
+ let rtp = s:rtp(g:plugs[name])
+ execute 'set rtp-='.s:escrtp(rtp)
+ let after = globpath(rtp, 'after')
+ if isdirectory(after)
+ execute 'set rtp-='.s:escrtp(after)
+ endif
+ endfor
+endfunction
+
+function! s:reorg_rtp()
+ if !empty(s:first_rtp)
+ execute 'set rtp-='.s:first_rtp
+ execute 'set rtp-='.s:last_rtp
+ endif
+
+ " &rtp is modified from outside
+ if exists('s:prtp') && s:prtp !=# &rtp
+ call s:remove_rtp()
+ unlet! s:middle
+ endif
+
+ let s:middle = get(s:, 'middle', &rtp)
+ let rtps = map(s:loaded_names(), 's:rtp(g:plugs[v:val])')
+ let afters = filter(map(copy(rtps), 'globpath(v:val, "after")'), '!empty(v:val)')
+ let rtp = join(map(rtps, 'escape(v:val, ",")'), ',')
+ \ . ','.s:middle.','
+ \ . join(map(afters, 'escape(v:val, ",")'), ',')
+ let &rtp = substitute(substitute(rtp, ',,*', ',', 'g'), '^,\|,$', '', 'g')
+ let s:prtp = &rtp
+
+ if !empty(s:first_rtp)
+ execute 'set rtp^='.s:first_rtp
+ execute 'set rtp+='.s:last_rtp
+ endif
+endfunction
+
+function! s:doautocmd(...)
+ if exists('#'.join(a:000, '#'))
+ execute 'doautocmd' ((v:version > 703 || has('patch442')) ? '<nomodeline>' : '') join(a:000)
+ endif
+endfunction
+
+function! s:dobufread(names)
+ for name in a:names
+ let path = s:rtp(g:plugs[name]).'/**'
+ for dir in ['ftdetect', 'ftplugin']
+ if len(finddir(dir, path))
+ return s:doautocmd('BufRead')
+ endif
+ endfor
+ endfor
+endfunction
+
+function! plug#load(...)
+ if a:0 == 0
+ return s:err('Argument missing: plugin name(s) required')
+ endif
+ if !exists('g:plugs')
+ return s:err('plug#begin was not called')
+ endif
+ let unknowns = filter(copy(a:000), '!has_key(g:plugs, v:val)')
+ if !empty(unknowns)
+ let s = len(unknowns) > 1 ? 's' : ''
+ return s:err(printf('Unknown plugin%s: %s', s, join(unknowns, ', ')))
+ end
+ for name in a:000
+ call s:lod([name], ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
+ endfor
+ call s:dobufread(a:000)
+ return 1
+endfunction
+
+function! s:remove_triggers(name)
+ if !has_key(s:triggers, a:name)
+ return
+ endif
+ for cmd in s:triggers[a:name].cmd
+ execute 'silent! delc' cmd
+ endfor
+ for map in s:triggers[a:name].map
+ execute 'silent! unmap' map
+ execute 'silent! iunmap' map
+ endfor
+ call remove(s:triggers, a:name)
+endfunction
+
+function! s:lod(names, types, ...)
+ for name in a:names
+ call s:remove_triggers(name)
+ let s:loaded[name] = 1
+ endfor
+ call s:reorg_rtp()
+
+ for name in a:names
+ let rtp = s:rtp(g:plugs[name])
+ for dir in a:types
+ call s:source(rtp, dir.'/**/*.vim')
+ endfor
+ if a:0
+ if !s:source(rtp, a:1) && !empty(s:glob(rtp, a:2))
+ execute 'runtime' a:1
+ endif
+ call s:source(rtp, a:2)
+ endif
+ call s:doautocmd('User', name)
+ endfor
+endfunction
+
+function! s:lod_ft(pat, names)
+ let syn = 'syntax/'.a:pat.'.vim'
+ call s:lod(a:names, ['plugin', 'after/plugin'], syn, 'after/'.syn)
+ execute 'autocmd! PlugLOD FileType' a:pat
+ call s:doautocmd('filetypeplugin', 'FileType')
+ call s:doautocmd('filetypeindent', 'FileType')
+endfunction
+
+function! s:lod_cmd(cmd, bang, l1, l2, args, names)
+ call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
+ call s:dobufread(a:names)
+ execute printf('%s%s%s %s', (a:l1 == a:l2 ? '' : (a:l1.','.a:l2)), a:cmd, a:bang, a:args)
+endfunction
+
+function! s:lod_map(map, names, with_prefix, prefix)
+ call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
+ call s:dobufread(a:names)
+ let extra = ''
+ while 1
+ let c = getchar(0)
+ if c == 0
+ break
+ endif
+ let extra .= nr2char(c)
+ endwhile
+
+ if a:with_prefix
+ let prefix = v:count ? v:count : ''
+ let prefix .= '"'.v:register.a:prefix
+ if mode(1) == 'no'
+ if v:operator == 'c'
+ let prefix = "\<esc>" . prefix
+ endif
+ let prefix .= v:operator
+ endif
+ call feedkeys(prefix, 'n')
+ endif
+ call feedkeys(substitute(a:map, '^<Plug>', "\<Plug>", '') . extra)
+endfunction
+
+function! plug#(repo, ...)
+ if a:0 > 1
+ return s:err('Invalid number of arguments (1..2)')
+ endif
+
+ try
+ let repo = s:trim(a:repo)
+ let opts = a:0 == 1 ? s:parse_options(a:1) : s:base_spec
+ let name = get(opts, 'as', fnamemodify(repo, ':t:s?\.git$??'))
+ let spec = extend(s:infer_properties(name, repo), opts)
+ if !has_key(g:plugs, name)
+ call add(g:plugs_order, name)
+ endif
+ let g:plugs[name] = spec
+ let s:loaded[name] = get(s:loaded, name, 0)
+ catch
+ return s:err(v:exception)
+ endtry
+endfunction
+
+function! s:parse_options(arg)
+ let opts = copy(s:base_spec)
+ let type = type(a:arg)
+ if type == s:TYPE.string
+ let opts.tag = a:arg
+ elseif type == s:TYPE.dict
+ call extend(opts, a:arg)
+ if has_key(opts, 'dir')
+ let opts.dir = s:dirpath(expand(opts.dir))
+ endif
+ else
+ throw 'Invalid argument type (expected: string or dictionary)'
+ endif
+ return opts
+endfunction
+
+function! s:infer_properties(name, repo)
+ let repo = a:repo
+ if s:is_local_plug(repo)
+ return { 'dir': s:dirpath(expand(repo)) }
+ else
+ if repo =~ ':'
+ let uri = repo
+ else
+ if repo !~ '/'
+ let repo = 'vim-scripts/'. repo
+ endif
+ let fmt = get(g:, 'plug_url_format', 'https://git::@github.com/%s.git')
+ let uri = printf(fmt, repo)
+ endif
+ return { 'dir': s:dirpath(g:plug_home.'/'.a:name), 'uri': uri }
+ endif
+endfunction
+
+function! s:install(force, names)
+ call s:update_impl(0, a:force, a:names)
+endfunction
+
+function! s:update(force, names)
+ call s:update_impl(1, a:force, a:names)
+endfunction
+
+function! plug#helptags()
+ if !exists('g:plugs')
+ return s:err('plug#begin was not called')
+ endif
+ for spec in values(g:plugs)
+ let docd = join([spec.dir, 'doc'], '/')
+ if isdirectory(docd)
+ silent! execute 'helptags' s:esc(docd)
+ endif
+ endfor
+ return 1
+endfunction
+
+function! s:syntax()
+ syntax clear
+ syntax region plug1 start=/\%1l/ end=/\%2l/ contains=plugNumber
+ syntax region plug2 start=/\%2l/ end=/\%3l/ contains=plugBracket,plugX
+ syn match plugNumber /[0-9]\+[0-9.]*/ contained
+ syn match plugBracket /[[\]]/ contained
+ syn match plugX /x/ contained
+ syn match plugDash /^-/
+ syn match plugPlus /^+/
+ syn match plugStar /^*/
+ syn match plugMessage /\(^- \)\@<=.*/
+ syn match plugName /\(^- \)\@<=[^ ]*:/
+ syn match plugSha /\%(: \)\@<=[0-9a-f]\{4,}$/
+ syn match plugTag /(tag: [^)]\+)/
+ syn match plugInstall /\(^+ \)\@<=[^:]*/
+ syn match plugUpdate /\(^* \)\@<=[^:]*/
+ syn match plugCommit /^ \X*[0-9a-f]\{7} .*/ contains=plugRelDate,plugEdge,plugTag
+ syn match plugEdge /^ \X\+$/
+ syn match plugEdge /^ \X*/ contained nextgroup=plugSha
+ syn match plugSha /[0-9a-f]\{7}/ contained
+ syn match plugRelDate /([^)]*)$/ contained
+ syn match plugNotLoaded /(not loaded)$/
+ syn match plugError /^x.*/
+ syn region plugDeleted start=/^\~ .*/ end=/^\ze\S/
+ syn match plugH2 /^.*:\n-\+$/
+ syn keyword Function PlugInstall PlugStatus PlugUpdate PlugClean
+ hi def link plug1 Title
+ hi def link plug2 Repeat
+ hi def link plugH2 Type
+ hi def link plugX Exception
+ hi def link plugBracket Structure
+ hi def link plugNumber Number
+
+ hi def link plugDash Special
+ hi def link plugPlus Constant
+ hi def link plugStar Boolean
+
+ hi def link plugMessage Function
+ hi def link plugName Label
+ hi def link plugInstall Function
+ hi def link plugUpdate Type
+
+ hi def link plugError Error
+ hi def link plugDeleted Ignore
+ hi def link plugRelDate Comment
+ hi def link plugEdge PreProc
+ hi def link plugSha Identifier
+ hi def link plugTag Constant
+
+ hi def link plugNotLoaded Comment
+endfunction
+
+function! s:lpad(str, len)
+ return a:str . repeat(' ', a:len - len(a:str))
+endfunction
+
+function! s:lines(msg)
+ return split(a:msg, "[\r\n]")
+endfunction
+
+function! s:lastline(msg)
+ return get(s:lines(a:msg), -1, '')
+endfunction
+
+function! s:new_window()
+ execute get(g:, 'plug_window', 'vertical topleft new')
+endfunction
+
+function! s:plug_window_exists()
+ let buflist = tabpagebuflist(s:plug_tab)
+ return !empty(buflist) && index(buflist, s:plug_buf) >= 0
+endfunction
+
+function! s:switch_in()
+ if !s:plug_window_exists()
+ return 0
+ endif
+
+ if winbufnr(0) != s:plug_buf
+ let s:pos = [tabpagenr(), winnr(), winsaveview()]
+ execute 'normal!' s:plug_tab.'gt'
+ let winnr = bufwinnr(s:plug_buf)
+ execute winnr.'wincmd w'
+ call add(s:pos, winsaveview())
+ else
+ let s:pos = [winsaveview()]
+ endif
+
+ setlocal modifiable
+ return 1
+endfunction
+
+function! s:switch_out(...)
+ call winrestview(s:pos[-1])
+ setlocal nomodifiable
+ if a:0 > 0
+ execute a:1
+ endif
+
+ if len(s:pos) > 1
+ execute 'normal!' s:pos[0].'gt'
+ execute s:pos[1] 'wincmd w'
+ call winrestview(s:pos[2])
+ endif
+endfunction
+
+function! s:finish_bindings()
+ nnoremap <silent> <buffer> R :call <SID>retry()<cr>
+ nnoremap <silent> <buffer> D :PlugDiff<cr>
+ nnoremap <silent> <buffer> S :PlugStatus<cr>
+ nnoremap <silent> <buffer> U :call <SID>status_update()<cr>
+ xnoremap <silent> <buffer> U :call <SID>status_update()<cr>
+ nnoremap <silent> <buffer> ]] :silent! call <SID>section('')<cr>
+ nnoremap <silent> <buffer> [[ :silent! call <SID>section('b')<cr>
+endfunction
+
+function! s:prepare(...)
+ if empty(getcwd())
+ throw 'Invalid current working directory. Cannot proceed.'
+ endif
+
+ for evar in ['$GIT_DIR', '$GIT_WORK_TREE']
+ if exists(evar)
+ throw evar.' detected. Cannot proceed.'
+ endif
+ endfor
+
+ call s:job_abort()
+ if s:switch_in()
+ if b:plug_preview == 1
+ pc
+ endif
+ enew
+ else
+ call s:new_window()
+ endif
+
+ nnoremap <silent> <buffer> q :if b:plug_preview==1<bar>pc<bar>endif<bar>bd<cr>
+ if a:0 == 0
+ call s:finish_bindings()
+ endif
+ let b:plug_preview = -1
+ let s:plug_tab = tabpagenr()
+ let s:plug_buf = winbufnr(0)
+ call s:assign_name()
+
+ for k in ['<cr>', 'L', 'o', 'X', 'd', 'dd']
+ execute 'silent! unmap <buffer>' k
+ endfor
+ setlocal buftype=nofile bufhidden=wipe nobuflisted nolist noswapfile nowrap cursorline modifiable
+ setf vim-plug
+ if exists('g:syntax_on')
+ call s:syntax()
+ endif
+endfunction
+
+function! s:assign_name()
+ " Assign buffer name
+ let prefix = '[Plugins]'
+ let name = prefix
+ let idx = 2
+ while bufexists(name)
+ let name = printf('%s (%s)', prefix, idx)
+ let idx = idx + 1
+ endwhile
+ silent! execute 'f' fnameescape(name)
+endfunction
+
+function! s:chsh(swap)
+ let prev = [&shell, &shellredir]
+ if !s:is_win && a:swap
+ set shell=sh shellredir=>%s\ 2>&1
+ endif
+ return prev
+endfunction
+
+function! s:bang(cmd, ...)
+ try
+ let [sh, shrd] = s:chsh(a:0)
+ " FIXME: Escaping is incomplete. We could use shellescape with eval,
+ " but it won't work on Windows.
+ let cmd = a:0 ? s:with_cd(a:cmd, a:1) : a:cmd
+ let g:_plug_bang = '!'.escape(cmd, '#!%')
+ execute "normal! :execute g:_plug_bang\<cr>\<cr>"
+ finally
+ unlet g:_plug_bang
+ let [&shell, &shellredir] = [sh, shrd]
+ endtry
+ return v:shell_error ? 'Exit status: ' . v:shell_error : ''
+endfunction
+
+function! s:regress_bar()
+ let bar = substitute(getline(2)[1:-2], '.*\zs=', 'x', '')
+ call s:progress_bar(2, bar, len(bar))
+endfunction
+
+function! s:is_updated(dir)
+ return !empty(s:system_chomp('git log --pretty=format:"%h" "HEAD...HEAD@{1}"', a:dir))
+endfunction
+
+function! s:do(pull, force, todo)
+ for [name, spec] in items(a:todo)
+ if !isdirectory(spec.dir)
+ continue
+ endif
+ let installed = has_key(s:update.new, name)
+ let updated = installed ? 0 :
+ \ (a:pull && index(s:update.errors, name) < 0 && s:is_updated(spec.dir))
+ if a:force || installed || updated
+ execute 'cd' s:esc(spec.dir)
+ call append(3, '- Post-update hook for '. name .' ... ')
+ let error = ''
+ let type = type(spec.do)
+ if type == s:TYPE.string
+ if spec.do[0] == ':'
+ call s:load_plugin(spec)
+ try
+ execute spec.do[1:]
+ catch
+ let error = v:exception
+ endtry
+ if !s:plug_window_exists()
+ cd -
+ throw 'Warning: vim-plug was terminated by the post-update hook of '.name
+ endif
+ else
+ let error = s:bang(spec.do)
+ endif
+ elseif type == s:TYPE.funcref
+ try
+ let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged')
+ call spec.do({ 'name': name, 'status': status, 'force': a:force })
+ catch
+ let error = v:exception
+ endtry
+ else
+ let error = 'Invalid hook type'
+ endif
+ call s:switch_in()
+ call setline(4, empty(error) ? (getline(4) . 'OK')
+ \ : ('x' . getline(4)[1:] . error))
+ if !empty(error)
+ call add(s:update.errors, name)
+ call s:regress_bar()
+ endif
+ cd -
+ endif
+ endfor
+endfunction
+
+function! s:hash_match(a, b)
+ return stridx(a:a, a:b) == 0 || stridx(a:b, a:a) == 0
+endfunction
+
+function! s:checkout(spec)
+ let sha = a:spec.commit
+ let output = s:system('git rev-parse HEAD', a:spec.dir)
+ if !v:shell_error && !s:hash_match(sha, s:lines(output)[0])
+ let output = s:system(
+ \ 'git fetch --depth 999999 && git checkout '.s:esc(sha), a:spec.dir)
+ endif
+ return output
+endfunction
+
+function! s:finish(pull)
+ let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen'))
+ if new_frozen
+ let s = new_frozen > 1 ? 's' : ''
+ call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s))
+ endif
+ call append(3, '- Finishing ... ') | 4
+ redraw
+ call plug#helptags()
+ call plug#end()
+ call setline(4, getline(4) . 'Done!')
+ redraw
+ let msgs = []
+ if !empty(s:update.errors)
+ call add(msgs, "Press 'R' to retry.")
+ endif
+ if a:pull && len(s:update.new) < len(filter(getline(5, '$'),
+ \ "v:val =~ '^- ' && stridx(v:val, 'Already up-to-date') < 0"))
+ call add(msgs, "Press 'D' to see the updated changes.")
+ endif
+ echo join(msgs, ' ')
+ call s:finish_bindings()
+endfunction
+
+function! s:retry()
+ if empty(s:update.errors)
+ return
+ endif
+ echo
+ call s:update_impl(s:update.pull, s:update.force,
+ \ extend(copy(s:update.errors), [s:update.threads]))
+endfunction
+
+function! s:is_managed(name)
+ return has_key(g:plugs[a:name], 'uri')
+endfunction
+
+function! s:names(...)
+ return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)'))
+endfunction
+
+function! s:check_ruby()
+ silent! ruby require 'thread'; VIM::command("let g:plug_ruby = '#{RUBY_VERSION}'")
+ if !exists('g:plug_ruby')
+ redraw!
+ return s:warn('echom', 'Warning: Ruby interface is broken')
+ endif
+ let ruby_version = split(g:plug_ruby, '\.')
+ unlet g:plug_ruby
+ return s:version_requirement(ruby_version, [1, 8, 7])
+endfunction
+
+function! s:update_impl(pull, force, args) abort
+ let args = copy(a:args)
+ let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ?
+ \ remove(args, -1) : get(g:, 'plug_threads', 16)
+
+ let managed = filter(copy(g:plugs), 's:is_managed(v:key)')
+ let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') :
+ \ filter(managed, 'index(args, v:key) >= 0')
+
+ if empty(todo)
+ return s:warn('echo', 'No plugin to '. (a:pull ? 'update' : 'install'))
+ endif
+
+ if !s:is_win && s:git_version_requirement(2, 3)
+ let s:git_terminal_prompt = exists('$GIT_TERMINAL_PROMPT') ? $GIT_TERMINAL_PROMPT : ''
+ let $GIT_TERMINAL_PROMPT = 0
+ for plug in values(todo)
+ let plug.uri = substitute(plug.uri,
+ \ '^https://git::@github\.com', 'https://github.com', '')
+ endfor
+ endif
+
+ if !isdirectory(g:plug_home)
+ try
+ call mkdir(g:plug_home, 'p')
+ catch
+ return s:err(printf('Invalid plug directory: %s. '.
+ \ 'Try to call plug#begin with a valid directory', g:plug_home))
+ endtry
+ endif
+
+ if has('nvim') && !exists('*jobwait') && threads > 1
+ call s:warn('echom', '[vim-plug] Update Neovim for parallel installer')
+ endif
+
+ let use_job = s:nvim || s:vim8
+ let python = (has('python') || has('python3')) && !use_job
+ let ruby = has('ruby') && !use_job && (v:version >= 703 || v:version == 702 && has('patch374')) && !(s:is_win && has('gui_running')) && s:check_ruby()
+
+ let s:update = {
+ \ 'start': reltime(),
+ \ 'all': todo,
+ \ 'todo': copy(todo),
+ \ 'errors': [],
+ \ 'pull': a:pull,
+ \ 'force': a:force,
+ \ 'new': {},
+ \ 'threads': (python || ruby || use_job) ? min([len(todo), threads]) : 1,
+ \ 'bar': '',
+ \ 'fin': 0
+ \ }
+
+ call s:prepare(1)
+ call append(0, ['', ''])
+ normal! 2G
+ silent! redraw
+
+ let s:clone_opt = get(g:, 'plug_shallow', 1) ?
+ \ '--depth 1' . (s:git_version_requirement(1, 7, 10) ? ' --no-single-branch' : '') : ''
+
+ " Python version requirement (>= 2.7)
+ if python && !has('python3') && !ruby && !use_job && s:update.threads > 1
+ redir => pyv
+ silent python import platform; print platform.python_version()
+ redir END
+ let python = s:version_requirement(
+ \ map(split(split(pyv)[0], '\.'), 'str2nr(v:val)'), [2, 6])
+ endif
+
+ if (python || ruby) && s:update.threads > 1
+ try
+ let imd = &imd
+ if s:mac_gui
+ set noimd
+ endif
+ if ruby
+ call s:update_ruby()
+ else
+ call s:update_python()
+ endif
+ catch
+ let lines = getline(4, '$')
+ let printed = {}
+ silent! 4,$d _
+ for line in lines
+ let name = s:extract_name(line, '.', '')
+ if empty(name) || !has_key(printed, name)
+ call append('$', line)
+ if !empty(name)
+ let printed[name] = 1
+ if line[0] == 'x' && index(s:update.errors, name) < 0
+ call add(s:update.errors, name)
+ end
+ endif
+ endif
+ endfor
+ finally
+ let &imd = imd
+ call s:update_finish()
+ endtry
+ else
+ call s:update_vim()
+ while use_job && has('vim_starting')
+ sleep 100m
+ if s:update.fin
+ break
+ endif
+ endwhile
+ endif
+endfunction
+
+function! s:log4(name, msg)
+ call setline(4, printf('- %s (%s)', a:msg, a:name))
+ redraw
+endfunction
+
+function! s:update_finish()
+ if exists('s:git_terminal_prompt')
+ let $GIT_TERMINAL_PROMPT = s:git_terminal_prompt
+ endif
+ if s:switch_in()
+ call append(3, '- Updating ...') | 4
+ for [name, spec] in items(filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && (s:update.force || s:update.pull || has_key(s:update.new, v:key))'))
+ let [pos, _] = s:logpos(name)
+ if !pos
+ continue
+ endif
+ if has_key(spec, 'commit')
+ call s:log4(name, 'Checking out '.spec.commit)
+ let out = s:checkout(spec)
+ elseif has_key(spec, 'tag')
+ let tag = spec.tag
+ if tag =~ '\*'
+ let tags = s:lines(s:system('git tag --list '.string(tag).' --sort -version:refname 2>&1', spec.dir))
+ if !v:shell_error && !empty(tags)
+ let tag = tags[0]
+ call s:log4(name, printf('Latest tag for %s -> %s', spec.tag, tag))
+ call append(3, '')
+ endif
+ endif
+ call s:log4(name, 'Checking out '.tag)
+ let out = s:system('git checkout -q '.s:esc(tag).' 2>&1', spec.dir)
+ else
+ let branch = s:esc(get(spec, 'branch', 'master'))
+ call s:log4(name, 'Merging origin/'.branch)
+ let out = s:system('git checkout -q '.branch.' 2>&1'
+ \. (has_key(s:update.new, name) ? '' : ('&& git merge --ff-only origin/'.branch.' 2>&1')), spec.dir)
+ endif
+ if !v:shell_error && filereadable(spec.dir.'/.gitmodules') &&
+ \ (s:update.force || has_key(s:update.new, name) || s:is_updated(spec.dir))
+ call s:log4(name, 'Updating submodules. This may take a while.')
+ let out .= s:bang('git submodule update --init --recursive 2>&1', spec.dir)
+ endif
+ let msg = s:format_message(v:shell_error ? 'x': '-', name, out)
+ if v:shell_error
+ call add(s:update.errors, name)
+ call s:regress_bar()
+ silent execute pos 'd _'
+ call append(4, msg) | 4
+ elseif !empty(out)
+ call setline(pos, msg[0])
+ endif
+ redraw
+ endfor
+ silent 4 d _
+ try
+ call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && has_key(v:val, "do")'))
+ catch
+ call s:warn('echom', v:exception)
+ call s:warn('echo', '')
+ return
+ endtry
+ call s:finish(s:update.pull)
+ call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.')
+ call s:switch_out('normal! gg')
+ endif
+endfunction
+
+function! s:job_abort()
+ if (!s:nvim && !s:vim8) || !exists('s:jobs')
+ return
+ endif
+
+ for [name, j] in items(s:jobs)
+ if s:nvim
+ silent! call jobstop(j.jobid)
+ elseif s:vim8
+ silent! call job_stop(j.jobid)
+ endif
+ if j.new
+ call s:system('rm -rf ' . s:shellesc(g:plugs[name].dir))
+ endif
+ endfor
+ let s:jobs = {}
+endfunction
+
+function! s:last_non_empty_line(lines)
+ let len = len(a:lines)
+ for idx in range(len)
+ let line = a:lines[len-idx-1]
+ if !empty(line)
+ return line
+ endif
+ endfor
+ return ''
+endfunction
+
+function! s:job_out_cb(self, data) abort
+ let self = a:self
+ let data = remove(self.lines, -1) . a:data
+ let lines = map(split(data, "\n", 1), 'split(v:val, "\r", 1)[-1]')
+ call extend(self.lines, lines)
+ " To reduce the number of buffer updates
+ let self.tick = get(self, 'tick', -1) + 1
+ if !self.running || self.tick % len(s:jobs) == 0
+ let bullet = self.running ? (self.new ? '+' : '*') : (self.error ? 'x' : '-')
+ let result = self.error ? join(self.lines, "\n") : s:last_non_empty_line(self.lines)
+ call s:log(bullet, self.name, result)
+ endif
+endfunction
+
+function! s:job_exit_cb(self, data) abort
+ let a:self.running = 0
+ let a:self.error = a:data != 0
+ call s:reap(a:self.name)
+ call s:tick()
+endfunction
+
+function! s:job_cb(fn, job, ch, data)
+ if !s:plug_window_exists() " plug window closed
+ return s:job_abort()
+ endif
+ call call(a:fn, [a:job, a:data])
+endfunction
+
+function! s:nvim_cb(job_id, data, event) abort
+ return a:event == 'stdout' ?
+ \ s:job_cb('s:job_out_cb', self, 0, join(a:data, "\n")) :
+ \ s:job_cb('s:job_exit_cb', self, 0, a:data)
+endfunction
+
+function! s:spawn(name, cmd, opts)
+ let job = { 'name': a:name, 'running': 1, 'error': 0, 'lines': [''],
+ \ 'new': get(a:opts, 'new', 0) }
+ let s:jobs[a:name] = job
+ let argv = add(s:is_win ? ['cmd', '/c'] : ['sh', '-c'],
+ \ has_key(a:opts, 'dir') ? s:with_cd(a:cmd, a:opts.dir) : a:cmd)
+
+ if s:nvim
+ call extend(job, {
+ \ 'on_stdout': function('s:nvim_cb'),
+ \ 'on_exit': function('s:nvim_cb'),
+ \ })
+ let jid = jobstart(argv, job)
+ if jid > 0
+ let job.jobid = jid
+ else
+ let job.running = 0
+ let job.error = 1
+ let job.lines = [jid < 0 ? argv[0].' is not executable' :
+ \ 'Invalid arguments (or job table is full)']
+ endif
+ elseif s:vim8
+ let jid = job_start(argv, {
+ \ 'out_cb': function('s:job_cb', ['s:job_out_cb', job]),
+ \ 'exit_cb': function('s:job_cb', ['s:job_exit_cb', job]),
+ \ 'out_mode': 'raw'
+ \})
+ if job_status(jid) == 'run'
+ let job.jobid = jid
+ else
+ let job.running = 0
+ let job.error = 1
+ let job.lines = ['Failed to start job']
+ endif
+ else
+ let params = has_key(a:opts, 'dir') ? [a:cmd, a:opts.dir] : [a:cmd]
+ let job.lines = s:lines(call('s:system', params))
+ let job.error = v:shell_error != 0
+ let job.running = 0
+ endif
+endfunction
+
+function! s:reap(name)
+ let job = s:jobs[a:name]
+ if job.error
+ call add(s:update.errors, a:name)
+ elseif get(job, 'new', 0)
+ let s:update.new[a:name] = 1
+ endif
+ let s:update.bar .= job.error ? 'x' : '='
+
+ let bullet = job.error ? 'x' : '-'
+ let result = job.error ? join(job.lines, "\n") : s:last_non_empty_line(job.lines)
+ call s:log(bullet, a:name, empty(result) ? 'OK' : result)
+ call s:bar()
+
+ call remove(s:jobs, a:name)
+endfunction
+
+function! s:bar()
+ if s:switch_in()
+ let total = len(s:update.all)
+ call setline(1, (s:update.pull ? 'Updating' : 'Installing').
+ \ ' plugins ('.len(s:update.bar).'/'.total.')')
+ call s:progress_bar(2, s:update.bar, total)
+ call s:switch_out()
+ endif
+endfunction
+
+function! s:logpos(name)
+ for i in range(4, line('$'))
+ if getline(i) =~# '^[-+x*] '.a:name.':'
+ for j in range(i + 1, line('$'))
+ if getline(j) !~ '^ '
+ return [i, j - 1]
+ endif
+ endfor
+ return [i, i]
+ endif
+ endfor
+ return [0, 0]
+endfunction
+
+function! s:log(bullet, name, lines)
+ if s:switch_in()
+ let [b, e] = s:logpos(a:name)
+ if b > 0
+ silent execute printf('%d,%d d _', b, e)
+ if b > winheight('.')
+ let b = 4
+ endif
+ else
+ let b = 4
+ endif
+ " FIXME For some reason, nomodifiable is set after :d in vim8
+ setlocal modifiable
+ call append(b - 1, s:format_message(a:bullet, a:name, a:lines))
+ call s:switch_out()
+ endif
+endfunction
+
+function! s:update_vim()
+ let s:jobs = {}
+
+ call s:bar()
+ call s:tick()
+endfunction
+
+function! s:tick()
+ let pull = s:update.pull
+ let prog = s:progress_opt(s:nvim || s:vim8)
+while 1 " Without TCO, Vim stack is bound to explode
+ if empty(s:update.todo)
+ if empty(s:jobs) && !s:update.fin
+ call s:update_finish()
+ let s:update.fin = 1
+ endif
+ return
+ endif
+
+ let name = keys(s:update.todo)[0]
+ let spec = remove(s:update.todo, name)
+ let new = !isdirectory(spec.dir)
+
+ call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...')
+ redraw
+
+ let has_tag = has_key(spec, 'tag')
+ if !new
+ let [error, _] = s:git_validate(spec, 0)
+ if empty(error)
+ if pull
+ let fetch_opt = (has_tag && !empty(globpath(spec.dir, '.git/shallow'))) ? '--depth 99999999' : ''
+ call s:spawn(name, printf('git fetch %s %s 2>&1', fetch_opt, prog), { 'dir': spec.dir })
+ else
+ let s:jobs[name] = { 'running': 0, 'lines': ['Already installed'], 'error': 0 }
+ endif
+ else
+ let s:jobs[name] = { 'running': 0, 'lines': s:lines(error), 'error': 1 }
+ endif
+ else
+ call s:spawn(name,
+ \ printf('git clone %s %s %s %s 2>&1',
+ \ has_tag ? '' : s:clone_opt,
+ \ prog,
+ \ s:shellesc(spec.uri),
+ \ s:shellesc(s:trim(spec.dir))), { 'new': 1 })
+ endif
+
+ if !s:jobs[name].running
+ call s:reap(name)
+ endif
+ if len(s:jobs) >= s:update.threads
+ break
+ endif
+endwhile
+endfunction
+
+function! s:update_python()
+let py_exe = has('python') ? 'python' : 'python3'
+execute py_exe "<< EOF"
+import datetime
+import functools
+import os
+try:
+ import queue
+except ImportError:
+ import Queue as queue
+import random
+import re
+import shutil
+import signal
+import subprocess
+import tempfile
+import threading as thr
+import time
+import traceback
+import vim
+
+G_NVIM = vim.eval("has('nvim')") == '1'
+G_PULL = vim.eval('s:update.pull') == '1'
+G_RETRIES = int(vim.eval('get(g:, "plug_retries", 2)')) + 1
+G_TIMEOUT = int(vim.eval('get(g:, "plug_timeout", 60)'))
+G_CLONE_OPT = vim.eval('s:clone_opt')
+G_PROGRESS = vim.eval('s:progress_opt(1)')
+G_LOG_PROB = 1.0 / int(vim.eval('s:update.threads'))
+G_STOP = thr.Event()
+G_IS_WIN = vim.eval('s:is_win') == '1'
+
+class PlugError(Exception):
+ def __init__(self, msg):
+ self.msg = msg
+class CmdTimedOut(PlugError):
+ pass
+class CmdFailed(PlugError):
+ pass
+class InvalidURI(PlugError):
+ pass
+class Action(object):
+ INSTALL, UPDATE, ERROR, DONE = ['+', '*', 'x', '-']
+
+class Buffer(object):
+ def __init__(self, lock, num_plugs, is_pull):
+ self.bar = ''
+ self.event = 'Updating' if is_pull else 'Installing'
+ self.lock = lock
+ self.maxy = int(vim.eval('winheight(".")'))
+ self.num_plugs = num_plugs
+
+ def __where(self, name):
+ """ Find first line with name in current buffer. Return line num. """
+ found, lnum = False, 0
+ matcher = re.compile('^[-+x*] {0}:'.format(name))
+ for line in vim.current.buffer:
+ if matcher.search(line) is not None:
+ found = True
+ break
+ lnum += 1
+
+ if not found:
+ lnum = -1
+ return lnum
+
+ def header(self):
+ curbuf = vim.current.buffer
+ curbuf[0] = self.event + ' plugins ({0}/{1})'.format(len(self.bar), self.num_plugs)
+
+ num_spaces = self.num_plugs - len(self.bar)
+ curbuf[1] = '[{0}{1}]'.format(self.bar, num_spaces * ' ')
+
+ with self.lock:
+ vim.command('normal! 2G')
+ vim.command('redraw')
+
+ def write(self, action, name, lines):
+ first, rest = lines[0], lines[1:]
+ msg = ['{0} {1}{2}{3}'.format(action, name, ': ' if first else '', first)]
+ msg.extend([' ' + line for line in rest])
+
+ try:
+ if action == Action.ERROR:
+ self.bar += 'x'
+ vim.command("call add(s:update.errors, '{0}')".format(name))
+ elif action == Action.DONE:
+ self.bar += '='
+
+ curbuf = vim.current.buffer
+ lnum = self.__where(name)
+ if lnum != -1: # Found matching line num
+ del curbuf[lnum]
+ if lnum > self.maxy and action in set([Action.INSTALL, Action.UPDATE]):
+ lnum = 3
+ else:
+ lnum = 3
+ curbuf.append(msg, lnum)
+
+ self.header()
+ except vim.error:
+ pass
+
+class Command(object):
+ CD = 'cd /d' if G_IS_WIN else 'cd'
+
+ def __init__(self, cmd, cmd_dir=None, timeout=60, cb=None, clean=None):
+ self.cmd = cmd
+ if cmd_dir:
+ self.cmd = '{0} {1} && {2}'.format(Command.CD, cmd_dir, self.cmd)
+ self.timeout = timeout
+ self.callback = cb if cb else (lambda msg: None)
+ self.clean = clean if clean else (lambda: None)
+ self.proc = None
+
+ @property
+ def alive(self):
+ """ Returns true only if command still running. """
+ return self.proc and self.proc.poll() is None
+
+ def execute(self, ntries=3):
+ """ Execute the command with ntries if CmdTimedOut.
+ Returns the output of the command if no Exception.
+ """
+ attempt, finished, limit = 0, False, self.timeout
+
+ while not finished:
+ try:
+ attempt += 1
+ result = self.try_command()
+ finished = True
+ return result
+ except CmdTimedOut:
+ if attempt != ntries:
+ self.notify_retry()
+ self.timeout += limit
+ else:
+ raise
+
+ def notify_retry(self):
+ """ Retry required for command, notify user. """
+ for count in range(3, 0, -1):
+ if G_STOP.is_set():
+ raise KeyboardInterrupt
+ msg = 'Timeout. Will retry in {0} second{1} ...'.format(
+ count, 's' if count != 1 else '')
+ self.callback([msg])
+ time.sleep(1)
+ self.callback(['Retrying ...'])
+
+ def try_command(self):
+ """ Execute a cmd & poll for callback. Returns list of output.
+ Raises CmdFailed -> return code for Popen isn't 0
+ Raises CmdTimedOut -> command exceeded timeout without new output
+ """
+ first_line = True
+
+ try:
+ tfile = tempfile.NamedTemporaryFile(mode='w+b')
+ preexec_fn = not G_IS_WIN and os.setsid or None
+ self.proc = subprocess.Popen(self.cmd, stdout=tfile,
+ stderr=subprocess.STDOUT,
+ stdin=subprocess.PIPE, shell=True,
+ preexec_fn=preexec_fn)
+ thrd = thr.Thread(target=(lambda proc: proc.wait()), args=(self.proc,))
+ thrd.start()
+
+ thread_not_started = True
+ while thread_not_started:
+ try:
+ thrd.join(0.1)
+ thread_not_started = False
+ except RuntimeError:
+ pass
+
+ while self.alive:
+ if G_STOP.is_set():
+ raise KeyboardInterrupt
+
+ if first_line or random.random() < G_LOG_PROB:
+ first_line = False
+ line = '' if G_IS_WIN else nonblock_read(tfile.name)
+ if line:
+ self.callback([line])
+
+ time_diff = time.time() - os.path.getmtime(tfile.name)
+ if time_diff > self.timeout:
+ raise CmdTimedOut(['Timeout!'])
+
+ thrd.join(0.5)
+
+ tfile.seek(0)
+ result = [line.decode('utf-8', 'replace').rstrip() for line in tfile]
+
+ if self.proc.returncode != 0:
+ raise CmdFailed([''] + result)
+
+ return result
+ except:
+ self.terminate()
+ raise
+
+ def terminate(self):
+ """ Terminate process and cleanup. """
+ if self.alive:
+ if G_IS_WIN:
+ os.kill(self.proc.pid, signal.SIGINT)
+ else:
+ os.killpg(self.proc.pid, signal.SIGTERM)
+ self.clean()
+
+class Plugin(object):
+ def __init__(self, name, args, buf_q, lock):
+ self.name = name
+ self.args = args
+ self.buf_q = buf_q
+ self.lock = lock
+ self.tag = args.get('tag', 0)
+
+ def manage(self):
+ try:
+ if os.path.exists(self.args['dir']):
+ self.update()
+ else:
+ self.install()
+ with self.lock:
+ thread_vim_command("let s:update.new['{0}'] = 1".format(self.name))
+ except PlugError as exc:
+ self.write(Action.ERROR, self.name, exc.msg)
+ except KeyboardInterrupt:
+ G_STOP.set()
+ self.write(Action.ERROR, self.name, ['Interrupted!'])
+ except:
+ # Any exception except those above print stack trace
+ msg = 'Trace:\n{0}'.format(traceback.format_exc().rstrip())
+ self.write(Action.ERROR, self.name, msg.split('\n'))
+ raise
+
+ def install(self):
+ target = self.args['dir']
+ if target[-1] == '\\':
+ target = target[0:-1]
+
+ def clean(target):
+ def _clean():
+ try:
+ shutil.rmtree(target)
+ except OSError:
+ pass
+ return _clean
+
+ self.write(Action.INSTALL, self.name, ['Installing ...'])
+ callback = functools.partial(self.write, Action.INSTALL, self.name)
+ cmd = 'git clone {0} {1} {2} {3} 2>&1'.format(
+ '' if self.tag else G_CLONE_OPT, G_PROGRESS, self.args['uri'],
+ esc(target))
+ com = Command(cmd, None, G_TIMEOUT, callback, clean(target))
+ result = com.execute(G_RETRIES)
+ self.write(Action.DONE, self.name, result[-1:])
+
+ def repo_uri(self):
+ cmd = 'git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url'
+ command = Command(cmd, self.args['dir'], G_TIMEOUT,)
+ result = command.execute(G_RETRIES)
+ return result[-1]
+
+ def update(self):
+ actual_uri = self.repo_uri()
+ expect_uri = self.args['uri']
+ regex = re.compile(r'^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$')
+ ma = regex.match(actual_uri)
+ mb = regex.match(expect_uri)
+ if ma is None or mb is None or ma.groups() != mb.groups():
+ msg = ['',
+ 'Invalid URI: {0}'.format(actual_uri),
+ 'Expected {0}'.format(expect_uri),
+ 'PlugClean required.']
+ raise InvalidURI(msg)
+
+ if G_PULL:
+ self.write(Action.UPDATE, self.name, ['Updating ...'])
+ callback = functools.partial(self.write, Action.UPDATE, self.name)
+ fetch_opt = '--depth 99999999' if self.tag and os.path.isfile(os.path.join(self.args['dir'], '.git/shallow')) else ''
+ cmd = 'git fetch {0} {1} 2>&1'.format(fetch_opt, G_PROGRESS)
+ com = Command(cmd, self.args['dir'], G_TIMEOUT, callback)
+ result = com.execute(G_RETRIES)
+ self.write(Action.DONE, self.name, result[-1:])
+ else:
+ self.write(Action.DONE, self.name, ['Already installed'])
+
+ def write(self, action, name, msg):
+ self.buf_q.put((action, name, msg))
+
+class PlugThread(thr.Thread):
+ def __init__(self, tname, args):
+ super(PlugThread, self).__init__()
+ self.tname = tname
+ self.args = args
+
+ def run(self):
+ thr.current_thread().name = self.tname
+ buf_q, work_q, lock = self.args
+
+ try:
+ while not G_STOP.is_set():
+ name, args = work_q.get_nowait()
+ plug = Plugin(name, args, buf_q, lock)
+ plug.manage()
+ work_q.task_done()
+ except queue.Empty:
+ pass
+
+class RefreshThread(thr.Thread):
+ def __init__(self, lock):
+ super(RefreshThread, self).__init__()
+ self.lock = lock
+ self.running = True
+
+ def run(self):
+ while self.running:
+ with self.lock:
+ thread_vim_command('noautocmd normal! a')
+ time.sleep(0.33)
+
+ def stop(self):
+ self.running = False
+
+if G_NVIM:
+ def thread_vim_command(cmd):
+ vim.session.threadsafe_call(lambda: vim.command(cmd))
+else:
+ def thread_vim_command(cmd):
+ vim.command(cmd)
+
+def esc(name):
+ return '"' + name.replace('"', '\"') + '"'
+
+def nonblock_read(fname):
+ """ Read a file with nonblock flag. Return the last line. """
+ fread = os.open(fname, os.O_RDONLY | os.O_NONBLOCK)
+ buf = os.read(fread, 100000).decode('utf-8', 'replace')
+ os.close(fread)
+
+ line = buf.rstrip('\r\n')
+ left = max(line.rfind('\r'), line.rfind('\n'))
+ if left != -1:
+ left += 1
+ line = line[left:]
+
+ return line
+
+def main():
+ thr.current_thread().name = 'main'
+ nthreads = int(vim.eval('s:update.threads'))
+ plugs = vim.eval('s:update.todo')
+ mac_gui = vim.eval('s:mac_gui') == '1'
+
+ lock = thr.Lock()
+ buf = Buffer(lock, len(plugs), G_PULL)
+ buf_q, work_q = queue.Queue(), queue.Queue()
+ for work in plugs.items():
+ work_q.put(work)
+
+ start_cnt = thr.active_count()
+ for num in range(nthreads):
+ tname = 'PlugT-{0:02}'.format(num)
+ thread = PlugThread(tname, (buf_q, work_q, lock))
+ thread.start()
+ if mac_gui:
+ rthread = RefreshThread(lock)
+ rthread.start()
+
+ while not buf_q.empty() or thr.active_count() != start_cnt:
+ try:
+ action, name, msg = buf_q.get(True, 0.25)
+ buf.write(action, name, ['OK'] if not msg else msg)
+ buf_q.task_done()
+ except queue.Empty:
+ pass
+ except KeyboardInterrupt:
+ G_STOP.set()
+
+ if mac_gui:
+ rthread.stop()
+ rthread.join()
+
+main()
+EOF
+endfunction
+
+function! s:update_ruby()
+ ruby << EOF
+ module PlugStream
+ SEP = ["\r", "\n", nil]
+ def get_line
+ buffer = ''
+ loop do
+ char = readchar rescue return
+ if SEP.include? char.chr
+ buffer << $/
+ break
+ else
+ buffer << char
+ end
+ end
+ buffer
+ end
+ end unless defined?(PlugStream)
+
+ def esc arg
+ %["#{arg.gsub('"', '\"')}"]
+ end
+
+ def killall pid
+ pids = [pid]
+ if /mswin|mingw|bccwin/ =~ RUBY_PLATFORM
+ pids.each { |pid| Process.kill 'INT', pid.to_i rescue nil }
+ else
+ unless `which pgrep 2> /dev/null`.empty?
+ children = pids
+ until children.empty?
+ children = children.map { |pid|
+ `pgrep -P #{pid}`.lines.map { |l| l.chomp }
+ }.flatten
+ pids += children
+ end
+ end
+ pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil }
+ end
+ end
+
+ def compare_git_uri a, b
+ regex = %r{^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$}
+ regex.match(a).to_a.drop(1) == regex.match(b).to_a.drop(1)
+ end
+
+ require 'thread'
+ require 'fileutils'
+ require 'timeout'
+ running = true
+ iswin = VIM::evaluate('s:is_win').to_i == 1
+ pull = VIM::evaluate('s:update.pull').to_i == 1
+ base = VIM::evaluate('g:plug_home')
+ all = VIM::evaluate('s:update.todo')
+ limit = VIM::evaluate('get(g:, "plug_timeout", 60)')
+ tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1
+ nthr = VIM::evaluate('s:update.threads').to_i
+ maxy = VIM::evaluate('winheight(".")').to_i
+ cd = iswin ? 'cd /d' : 'cd'
+ tot = VIM::evaluate('len(s:update.todo)') || 0
+ bar = ''
+ skip = 'Already installed'
+ mtx = Mutex.new
+ take1 = proc { mtx.synchronize { running && all.shift } }
+ logh = proc {
+ cnt = bar.length
+ $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})"
+ $curbuf[2] = '[' + bar.ljust(tot) + ']'
+ VIM::command('normal! 2G')
+ VIM::command('redraw')
+ }
+ where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } }
+ log = proc { |name, result, type|
+ mtx.synchronize do
+ ing = ![true, false].include?(type)
+ bar += type ? '=' : 'x' unless ing
+ b = case type
+ when :install then '+' when :update then '*'
+ when true, nil then '-' else
+ VIM::command("call add(s:update.errors, '#{name}')")
+ 'x'
+ end
+ result =
+ if type || type.nil?
+ ["#{b} #{name}: #{result.lines.to_a.last || 'OK'}"]
+ elsif result =~ /^Interrupted|^Timeout/
+ ["#{b} #{name}: #{result}"]
+ else
+ ["#{b} #{name}"] + result.lines.map { |l| " " << l }
+ end
+ if lnum = where.call(name)
+ $curbuf.delete lnum
+ lnum = 4 if ing && lnum > maxy
+ end
+ result.each_with_index do |line, offset|
+ $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp)
+ end
+ logh.call
+ end
+ }
+ bt = proc { |cmd, name, type, cleanup|
+ tried = timeout = 0
+ begin
+ tried += 1
+ timeout += limit
+ fd = nil
+ data = ''
+ if iswin
+ Timeout::timeout(timeout) do
+ tmp = VIM::evaluate('tempname()')
+ system("(#{cmd}) > #{tmp}")
+ data = File.read(tmp).chomp
+ File.unlink tmp rescue nil
+ end
+ else
+ fd = IO.popen(cmd).extend(PlugStream)
+ first_line = true
+ log_prob = 1.0 / nthr
+ while line = Timeout::timeout(timeout) { fd.get_line }
+ data << line
+ log.call name, line.chomp, type if name && (first_line || rand < log_prob)
+ first_line = false
+ end
+ fd.close
+ end
+ [$? == 0, data.chomp]
+ rescue Timeout::Error, Interrupt => e
+ if fd && !fd.closed?
+ killall fd.pid
+ fd.close
+ end
+ cleanup.call if cleanup
+ if e.is_a?(Timeout::Error) && tried < tries
+ 3.downto(1) do |countdown|
+ s = countdown > 1 ? 's' : ''
+ log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type
+ sleep 1
+ end
+ log.call name, 'Retrying ...', type
+ retry
+ end
+ [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"]
+ end
+ }
+ main = Thread.current
+ threads = []
+ watcher = Thread.new {
+ require 'io/console' # >= Ruby 1.9
+ nil until IO.console.getch == 3.chr
+ mtx.synchronize do
+ running = false
+ threads.each { |t| t.raise Interrupt }
+ end
+ threads.each { |t| t.join rescue nil }
+ main.kill
+ }
+ refresh = Thread.new {
+ while true
+ mtx.synchronize do
+ break unless running
+ VIM::command('noautocmd normal! a')
+ end
+ sleep 0.2
+ end
+ } if VIM::evaluate('s:mac_gui') == 1
+
+ clone_opt = VIM::evaluate('s:clone_opt')
+ progress = VIM::evaluate('s:progress_opt(1)')
+ nthr.times do
+ mtx.synchronize do
+ threads << Thread.new {
+ while pair = take1.call
+ name = pair.first
+ dir, uri, tag = pair.last.values_at *%w[dir uri tag]
+ exists = File.directory? dir
+ ok, result =
+ if exists
+ chdir = "#{cd} #{iswin ? dir : esc(dir)}"
+ ret, data = bt.call "#{chdir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url", nil, nil, nil
+ current_uri = data.lines.to_a.last
+ if !ret
+ if data =~ /^Interrupted|^Timeout/
+ [false, data]
+ else
+ [false, [data.chomp, "PlugClean required."].join($/)]
+ end
+ elsif !compare_git_uri(current_uri, uri)
+ [false, ["Invalid URI: #{current_uri}",
+ "Expected: #{uri}",
+ "PlugClean required."].join($/)]
+ else
+ if pull
+ log.call name, 'Updating ...', :update
+ fetch_opt = (tag && File.exist?(File.join(dir, '.git/shallow'))) ? '--depth 99999999' : ''
+ bt.call "#{chdir} && git fetch #{fetch_opt} #{progress} 2>&1", name, :update, nil
+ else
+ [true, skip]
+ end
+ end
+ else
+ d = esc dir.sub(%r{[\\/]+$}, '')
+ log.call name, 'Installing ...', :install
+ bt.call "git clone #{clone_opt unless tag} #{progress} #{uri} #{d} 2>&1", name, :install, proc {
+ FileUtils.rm_rf dir
+ }
+ end
+ mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok
+ log.call name, result, ok
+ end
+ } if running
+ end
+ end
+ threads.each { |t| t.join rescue nil }
+ logh.call
+ refresh.kill if refresh
+ watcher.kill
+EOF
+endfunction
+
+function! s:shellesc(arg)
+ return '"'.escape(a:arg, '"').'"'
+endfunction
+
+function! s:glob_dir(path)
+ return map(filter(s:glob(a:path, '**'), 'isdirectory(v:val)'), 's:dirpath(v:val)')
+endfunction
+
+function! s:progress_bar(line, bar, total)
+ call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']')
+endfunction
+
+function! s:compare_git_uri(a, b)
+ " See `git help clone'
+ " https:// [user@] github.com[:port] / junegunn/vim-plug [.git]
+ " [git@] github.com[:port] : junegunn/vim-plug [.git]
+ " file:// / junegunn/vim-plug [/]
+ " / junegunn/vim-plug [/]
+ let pat = '^\%(\w\+://\)\='.'\%([^@/]*@\)\='.'\([^:/]*\%(:[0-9]*\)\=\)'.'[:/]'.'\(.\{-}\)'.'\%(\.git\)\=/\?$'
+ let ma = matchlist(a:a, pat)
+ let mb = matchlist(a:b, pat)
+ return ma[1:2] ==# mb[1:2]
+endfunction
+
+function! s:format_message(bullet, name, message)
+ if a:bullet != 'x'
+ return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))]
+ else
+ let lines = map(s:lines(a:message), '" ".v:val')
+ return extend([printf('x %s:', a:name)], lines)
+ endif
+endfunction
+
+function! s:with_cd(cmd, dir)
+ return printf('cd%s %s && %s', s:is_win ? ' /d' : '', s:shellesc(a:dir), a:cmd)
+endfunction
+
+function! s:system(cmd, ...)
+ try
+ let [sh, shrd] = s:chsh(1)
+ let cmd = a:0 > 0 ? s:with_cd(a:cmd, a:1) : a:cmd
+ return system(s:is_win ? '('.cmd.')' : cmd)
+ finally
+ let [&shell, &shellredir] = [sh, shrd]
+ endtry
+endfunction
+
+function! s:system_chomp(...)
+ let ret = call('s:system', a:000)
+ return v:shell_error ? '' : substitute(ret, '\n$', '', '')
+endfunction
+
+function! s:git_validate(spec, check_branch)
+ let err = ''
+ if isdirectory(a:spec.dir)
+ let result = s:lines(s:system('git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url', a:spec.dir))
+ let remote = result[-1]
+ if v:shell_error
+ let err = join([remote, 'PlugClean required.'], "\n")
+ elseif !s:compare_git_uri(remote, a:spec.uri)
+ let err = join(['Invalid URI: '.remote,
+ \ 'Expected: '.a:spec.uri,
+ \ 'PlugClean required.'], "\n")
+ elseif a:check_branch && has_key(a:spec, 'commit')
+ let result = s:lines(s:system('git rev-parse HEAD 2>&1', a:spec.dir))
+ let sha = result[-1]
+ if v:shell_error
+ let err = join(add(result, 'PlugClean required.'), "\n")
+ elseif !s:hash_match(sha, a:spec.commit)
+ let err = join([printf('Invalid HEAD (expected: %s, actual: %s)',
+ \ a:spec.commit[:6], sha[:6]),
+ \ 'PlugUpdate required.'], "\n")
+ endif
+ elseif a:check_branch
+ let branch = result[0]
+ " Check tag
+ if has_key(a:spec, 'tag')
+ let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir)
+ if a:spec.tag !=# tag
+ let err = printf('Invalid tag: %s (expected: %s). Try PlugUpdate.',
+ \ (empty(tag) ? 'N/A' : tag), a:spec.tag)
+ endif
+ " Check branch
+ elseif a:spec.branch !=# branch
+ let err = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.',
+ \ branch, a:spec.branch)
+ endif
+ if empty(err)
+ let commits = len(s:lines(s:system(printf('git rev-list origin/%s..HEAD', a:spec.branch), a:spec.dir)))
+ if !v:shell_error && commits
+ let err = join([printf('Diverged from origin/%s by %d commit(s).', a:spec.branch, commits),
+ \ 'Reinstall after PlugClean.'], "\n")
+ endif
+ endif
+ endif
+ else
+ let err = 'Not found'
+ endif
+ return [err, err =~# 'PlugClean']
+endfunction
+
+function! s:rm_rf(dir)
+ if isdirectory(a:dir)
+ call s:system((s:is_win ? 'rmdir /S /Q ' : 'rm -rf ') . s:shellesc(a:dir))
+ endif
+endfunction
+
+function! s:clean(force)
+ call s:prepare()
+ call append(0, 'Searching for invalid plugins in '.g:plug_home)
+ call append(1, '')
+
+ " List of valid directories
+ let dirs = []
+ let errs = {}
+ let [cnt, total] = [0, len(g:plugs)]
+ for [name, spec] in items(g:plugs)
+ if !s:is_managed(name)
+ call add(dirs, spec.dir)
+ else
+ let [err, clean] = s:git_validate(spec, 1)
+ if clean
+ let errs[spec.dir] = s:lines(err)[0]
+ else
+ call add(dirs, spec.dir)
+ endif
+ endif
+ let cnt += 1
+ call s:progress_bar(2, repeat('=', cnt), total)
+ normal! 2G
+ redraw
+ endfor
+
+ let allowed = {}
+ for dir in dirs
+ let allowed[s:dirpath(fnamemodify(dir, ':h:h'))] = 1
+ let allowed[dir] = 1
+ for child in s:glob_dir(dir)
+ let allowed[child] = 1
+ endfor
+ endfor
+
+ let todo = []
+ let found = sort(s:glob_dir(g:plug_home))
+ while !empty(found)
+ let f = remove(found, 0)
+ if !has_key(allowed, f) && isdirectory(f)
+ call add(todo, f)
+ call append(line('$'), '- ' . f)
+ if has_key(errs, f)
+ call append(line('$'), ' ' . errs[f])
+ endif
+ let found = filter(found, 'stridx(v:val, f) != 0')
+ end
+ endwhile
+
+ 4
+ redraw
+ if empty(todo)
+ call append(line('$'), 'Already clean.')
+ else
+ let s:clean_count = 0
+ call append(3, ['Directories to delete:', ''])
+ redraw!
+ if a:force || s:ask_no_interrupt('Delete all directories?')
+ call s:delete([6, line('$')], 1)
+ else
+ call setline(4, 'Cancelled.')
+ nnoremap <silent> <buffer> d :set opfunc=<sid>delete_op<cr>g@
+ nmap <silent> <buffer> dd d_
+ xnoremap <silent> <buffer> d :<c-u>call <sid>delete_op(visualmode(), 1)<cr>
+ echo 'Delete the lines (d{motion}) to delete the corresponding directories'
+ endif
+ endif
+ 4
+ setlocal nomodifiable
+endfunction
+
+function! s:delete_op(type, ...)
+ call s:delete(a:0 ? [line("'<"), line("'>")] : [line("'["), line("']")], 0)
+endfunction
+
+function! s:delete(range, force)
+ let [l1, l2] = a:range
+ let force = a:force
+ while l1 <= l2
+ let line = getline(l1)
+ if line =~ '^- ' && isdirectory(line[2:])
+ execute l1
+ redraw!
+ let answer = force ? 1 : s:ask('Delete '.line[2:].'?', 1)
+ let force = force || answer > 1
+ if answer
+ call s:rm_rf(line[2:])
+ setlocal modifiable
+ call setline(l1, '~'.line[1:])
+ let s:clean_count += 1
+ call setline(4, printf('Removed %d directories.', s:clean_count))
+ setlocal nomodifiable
+ endif
+ endif
+ let l1 += 1
+ endwhile
+endfunction
+
+function! s:upgrade()
+ echo 'Downloading the latest version of vim-plug'
+ redraw
+ let tmp = tempname()
+ let new = tmp . '/plug.vim'
+
+ try
+ let out = s:system(printf('git clone --depth 1 %s %s', s:plug_src, tmp))
+ if v:shell_error
+ return s:err('Error upgrading vim-plug: '. out)
+ endif
+
+ if readfile(s:me) ==# readfile(new)
+ echo 'vim-plug is already up-to-date'
+ return 0
+ else
+ call rename(s:me, s:me . '.old')
+ call rename(new, s:me)
+ unlet g:loaded_plug
+ echo 'vim-plug has been upgraded'
+ return 1
+ endif
+ finally
+ silent! call s:rm_rf(tmp)
+ endtry
+endfunction
+
+function! s:upgrade_specs()
+ for spec in values(g:plugs)
+ let spec.frozen = get(spec, 'frozen', 0)
+ endfor
+endfunction
+
+function! s:status()
+ call s:prepare()
+ call append(0, 'Checking plugins')
+ call append(1, '')
+
+ let ecnt = 0
+ let unloaded = 0
+ let [cnt, total] = [0, len(g:plugs)]
+ for [name, spec] in items(g:plugs)
+ if has_key(spec, 'uri')
+ if isdirectory(spec.dir)
+ let [err, _] = s:git_validate(spec, 1)
+ let [valid, msg] = [empty(err), empty(err) ? 'OK' : err]
+ else
+ let [valid, msg] = [0, 'Not found. Try PlugInstall.']
+ endif
+ else
+ if isdirectory(spec.dir)
+ let [valid, msg] = [1, 'OK']
+ else
+ let [valid, msg] = [0, 'Not found.']
+ endif
+ endif
+ let cnt += 1
+ let ecnt += !valid
+ " `s:loaded` entry can be missing if PlugUpgraded
+ if valid && get(s:loaded, name, -1) == 0
+ let unloaded = 1
+ let msg .= ' (not loaded)'
+ endif
+ call s:progress_bar(2, repeat('=', cnt), total)
+ call append(3, s:format_message(valid ? '-' : 'x', name, msg))
+ normal! 2G
+ redraw
+ endfor
+ call setline(1, 'Finished. '.ecnt.' error(s).')
+ normal! gg
+ setlocal nomodifiable
+ if unloaded
+ echo "Press 'L' on each line to load plugin, or 'U' to update"
+ nnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
+ xnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
+ end
+endfunction
+
+function! s:extract_name(str, prefix, suffix)
+ return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$')
+endfunction
+
+function! s:status_load(lnum)
+ let line = getline(a:lnum)
+ let name = s:extract_name(line, '-', '(not loaded)')
+ if !empty(name)
+ call plug#load(name)
+ setlocal modifiable
+ call setline(a:lnum, substitute(line, ' (not loaded)$', '', ''))
+ setlocal nomodifiable
+ endif
+endfunction
+
+function! s:status_update() range
+ let lines = getline(a:firstline, a:lastline)
+ let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)')
+ if !empty(names)
+ echo
+ execute 'PlugUpdate' join(names)
+ endif
+endfunction
+
+function! s:is_preview_window_open()
+ silent! wincmd P
+ if &previewwindow
+ wincmd p
+ return 1
+ endif
+endfunction
+
+function! s:find_name(lnum)
+ for lnum in reverse(range(1, a:lnum))
+ let line = getline(lnum)
+ if empty(line)
+ return ''
+ endif
+ let name = s:extract_name(line, '-', '')
+ if !empty(name)
+ return name
+ endif
+ endfor
+ return ''
+endfunction
+
+function! s:preview_commit()
+ if b:plug_preview < 0
+ let b:plug_preview = !s:is_preview_window_open()
+ endif
+
+ let sha = matchstr(getline('.'), '^ \X*\zs[0-9a-f]\{7}')
+ if empty(sha)
+ return
+ endif
+
+ let name = s:find_name(line('.'))
+ if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir)
+ return
+ endif
+
+ if exists('g:plug_pwindow') && !s:is_preview_window_open()
+ execute g:plug_pwindow
+ execute 'e' sha
+ else
+ execute 'pedit' sha
+ wincmd P
+ endif
+ setlocal previewwindow filetype=git buftype=nofile nobuflisted modifiable
+ execute 'silent %!cd' s:shellesc(g:plugs[name].dir) '&& git show --no-color --pretty=medium' sha
+ setlocal nomodifiable
+ nnoremap <silent> <buffer> q :q<cr>
+ wincmd p
+endfunction
+
+function! s:section(flags)
+ call search('\(^[x-] \)\@<=[^:]\+:', a:flags)
+endfunction
+
+function! s:format_git_log(line)
+ let indent = ' '
+ let tokens = split(a:line, nr2char(1))
+ if len(tokens) != 5
+ return indent.substitute(a:line, '\s*$', '', '')
+ endif
+ let [graph, sha, refs, subject, date] = tokens
+ let tag = matchstr(refs, 'tag: [^,)]\+')
+ let tag = empty(tag) ? ' ' : ' ('.tag.') '
+ return printf('%s%s%s%s%s (%s)', indent, graph, sha, tag, subject, date)
+endfunction
+
+function! s:append_ul(lnum, text)
+ call append(a:lnum, ['', a:text, repeat('-', len(a:text))])
+endfunction
+
+function! s:diff()
+ call s:prepare()
+ call append(0, ['Collecting changes ...', ''])
+ let cnts = [0, 0]
+ let bar = ''
+ let total = filter(copy(g:plugs), 's:is_managed(v:key) && isdirectory(v:val.dir)')
+ call s:progress_bar(2, bar, len(total))
+ for origin in [1, 0]
+ let plugs = reverse(sort(items(filter(copy(total), (origin ? '' : '!').'(has_key(v:val, "commit") || has_key(v:val, "tag"))'))))
+ if empty(plugs)
+ continue
+ endif
+ call s:append_ul(2, origin ? 'Pending updates:' : 'Last update:')
+ for [k, v] in plugs
+ let range = origin ? '..origin/'.v.branch : 'HEAD@{1}..'
+ let diff = s:system_chomp('git log --graph --color=never --pretty=format:"%x01%h%x01%d%x01%s%x01%cr" '.s:shellesc(range), v.dir)
+ if !empty(diff)
+ let ref = has_key(v, 'tag') ? (' (tag: '.v.tag.')') : has_key(v, 'commit') ? (' '.v.commit) : ''
+ call append(5, extend(['', '- '.k.':'.ref], map(s:lines(diff), 's:format_git_log(v:val)')))
+ let cnts[origin] += 1
+ endif
+ let bar .= '='
+ call s:progress_bar(2, bar, len(total))
+ normal! 2G
+ redraw
+ endfor
+ if !cnts[origin]
+ call append(5, ['', 'N/A'])
+ endif
+ endfor
+ call setline(1, printf('%d plugin(s) updated.', cnts[0])
+ \ . (cnts[1] ? printf(' %d plugin(s) have pending updates.', cnts[1]) : ''))
+
+ if cnts[0] || cnts[1]
+ nnoremap <silent> <buffer> <cr> :silent! call <SID>preview_commit()<cr>
+ nnoremap <silent> <buffer> o :silent! call <SID>preview_commit()<cr>
+ endif
+ if cnts[0]
+ nnoremap <silent> <buffer> X :call <SID>revert()<cr>
+ echo "Press 'X' on each block to revert the update"
+ endif
+ normal! gg
+ setlocal nomodifiable
+endfunction
+
+function! s:revert()
+ if search('^Pending updates', 'bnW')
+ return
+ endif
+
+ let name = s:find_name(line('.'))
+ if empty(name) || !has_key(g:plugs, name) ||
+ \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y'
+ return
+ endif
+
+ call s:system('git reset --hard HEAD@{1} && git checkout '.s:esc(g:plugs[name].branch), g:plugs[name].dir)
+ setlocal modifiable
+ normal! "_dap
+ setlocal nomodifiable
+ echo 'Reverted'
+endfunction
+
+function! s:snapshot(force, ...) abort
+ call s:prepare()
+ setf vim
+ call append(0, ['" Generated by vim-plug',
+ \ '" '.strftime("%c"),
+ \ '" :source this file in vim to restore the snapshot',
+ \ '" or execute: vim -S snapshot.vim',
+ \ '', '', 'PlugUpdate!'])
+ 1
+ let anchor = line('$') - 3
+ let names = sort(keys(filter(copy(g:plugs),
+ \'has_key(v:val, "uri") && !has_key(v:val, "commit") && isdirectory(v:val.dir)')))
+ for name in reverse(names)
+ let sha = s:system_chomp('git rev-parse --short HEAD', g:plugs[name].dir)
+ if !empty(sha)
+ call append(anchor, printf("silent! let g:plugs['%s'].commit = '%s'", name, sha))
+ redraw
+ endif
+ endfor
+
+ if a:0 > 0
+ let fn = expand(a:1)
+ if filereadable(fn) && !(a:force || s:ask(a:1.' already exists. Overwrite?'))
+ return
+ endif
+ call writefile(getline(1, '$'), fn)
+ echo 'Saved as '.a:1
+ silent execute 'e' s:esc(fn)
+ setf vim
+ endif
+endfunction
+
+function! s:split_rtp()
+ return split(&rtp, '\\\@<!,')
+endfunction
+
+let s:first_rtp = s:escrtp(get(s:split_rtp(), 0, ''))
+let s:last_rtp = s:escrtp(get(s:split_rtp(), -1, ''))
+
+if exists('g:plugs')
+ let g:plugs_order = get(g:, 'plugs_order', keys(g:plugs))
+ call s:upgrade_specs()
+ call s:define_commands()
+endif
+
+let &cpo = s:cpo_save
+unlet s:cpo_save
diff --git a/nvim/init.vim b/nvim/init.vim
new file mode 100644
index 0000000..f90e75b
--- /dev/null
+++ b/nvim/init.vim
@@ -0,0 +1,12 @@
+call plug#begin('~/.vim/plugged')
+Plug 'jeffkreeftmeijer/neovim-sensible'
+Plug 'jeffkreeftmeijer/vim-dim'
+Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
+Plug 'junegunn/fzf.vim'
+Plug 'junegunn/goyo.vim'
+Plug 'kchmck/vim-coffee-script'
+Plug 'tpope/vim-commentary'
+Plug 'tpope/vim-fugitive'
+call plug#end()
+
+colors dim
|
rfelix/hostgitrb
|
95a7dff66aff103e58dfddc2f9ba4b857b9fc0e4
|
Bumped version to 0.0.2 due to mistake in regexp that didn't allow numbers in path
|
diff --git a/VERSION b/VERSION
index 8a9ecc2..4e379d2 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.0.1
\ No newline at end of file
+0.0.2
|
rfelix/hostgitrb
|
bc2bf5d2e219dd595e0e4afdffd634d8944328c5
|
git commit -m "Fixed regexp to allow numbers in paths. Close gh-1
|
diff --git a/lib/only_git.rb b/lib/only_git.rb
index 16095ba..9348683 100755
--- a/lib/only_git.rb
+++ b/lib/only_git.rb
@@ -1,42 +1,42 @@
#!/usr/bin/env ruby
require 'logger'
require File.join(File.dirname(__FILE__), '..', 'vendor', 'trollop.rb')
DEBUG_LEVEL = Logger::ERROR
#Examples of commands that are permitted and that are used by git (git clone/git fetch/git push/git pull)
# git-upload-pack '/home/user/repo/Notes.git'
# git-receive-pack '/home/user/repo/Notes.git'
# git-upload-pack 'Notes.git'
-GIT_R_REGEX = /^git[\-](upload)[\-]pack '([a-zA-Z\-_\/]+)([.]git)?'$/
-GIT_RW_REGEX = /^git[\-](upload|receive)[\-]pack '([a-zA-Z\-_\/]+)([.]git)?'$/
+GIT_R_REGEX = /^git[\-](upload)[\-]pack '([0-9a-zA-Z\-_\/]+)([.]git)?'$/
+GIT_RW_REGEX = /^git[\-](upload|receive)[\-]pack '([0-9a-zA-Z\-_\/]+)([.]git)?'$/
opts = Trollop::options do
opt :log, "Set log file", :default => File.join(File.dirname(__FILE__), 'debug.log')
opt :dir, "Set directory that contains git repositories", :default => ''
opt :readonly, "Set access to repositories under --dir to read only", :default => false
end
Trollop::die 'Directory with git repositories doesn\'t exist. Needs to be set with --dir' unless File.directory? opts[:dir]
logger = Logger.new(opts[:log], 'weekly')
logger.level = DEBUG_LEVEL
command = String.new(ENV['SSH_ORIGINAL_COMMAND'])
logger.debug("Received command: #{command}")
right_command = GIT_RW_REGEX
right_command = GIT_R_REGEX if opts[:readonly]
logger.debug('Access to repos under dir is set to: ' + (opts[:readonly] ? 'Read' : 'Read/Write'))
if command =~ right_command then
opts[:dir] = File.join(opts[:dir], '')
command.gsub!("-pack '", "-pack '#{opts[:dir]}")
logger.info("Executing command: #{command}")
exec command
else
logger.error("Received bad command")
exec 'echo NOT ALLOWED'
end
|
rfelix/hostgitrb
|
0d44e3e66e17c2e61ae810bde1be22a6f537b9c0
|
Changed Rakefile to use 'mg' gem for managing gem building/packaging Changed gemspec information and added 'mg' as a development dependency
|
diff --git a/.gitignore b/.gitignore
index 86339a0..95569d5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
-*.gem
\ No newline at end of file
+*.gem
+dist/*
\ No newline at end of file
diff --git a/Rakefile b/Rakefile
index b8bfe5e..f61b68e 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,26 +1,2 @@
-# ----- Utility Functions -----
-
-def scope(path)
- File.join(File.dirname(__FILE__), path)
-end
-
-# ----- Packaging -----
-
-require 'rake/gempackagetask'
-load scope('hostgitrb.gemspec')
-
-Rake::GemPackageTask.new(HOSTGITRB_GEMSPEC) do |pkg|
- if Rake.application.top_level_tasks.include?('release')
- pkg.need_tar_gz = true
- pkg.need_tar_bz2 = true
- pkg.need_zip = true
- end
-end
-
-desc "Install HostGitRb as a gem."
-task :install => [:package] do
- sudo = RUBY_PLATFORM =~ /win32|mingw/ ? '' : 'sudo'
- gem = RUBY_PLATFORM =~ /java/ ? 'jgem' : 'gem'
- #sh %{#{sudo} #{gem} install --no-ri pkg/hostgitrb-#{File.read(scope('VERSION')).strip}}
- sh %{#{gem} install --no-ri pkg/hostgitrb-#{File.read(scope('VERSION')).strip}}
-end
\ No newline at end of file
+require "mg"
+MG.new("hostgitrb.gemspec")
\ No newline at end of file
diff --git a/hostgitrb.gemspec b/hostgitrb.gemspec
index e2a2d02..58b1a84 100644
--- a/hostgitrb.gemspec
+++ b/hostgitrb.gemspec
@@ -1,18 +1,20 @@
# -*- encoding: utf-8 -*-
-require 'rubygems'
-require 'rake'
-HOSTGITRB_GEMSPEC = Gem::Specification.new do |spec|
+Gem::Specification.new do |spec|
spec.name = 'hostgitrb'
- spec.summary = "Simple Git repository hosting using SSH keys"
+ spec.summary = "Simple Git repository hosting using SSH Public Keys"
spec.version = File.read(File.dirname(__FILE__) + '/VERSION').strip
spec.authors = ['Raoul Felix']
- spec.email = '[email protected]'
+ spec.email = '[email protected]'
spec.description = <<-END
- This gem contains some simple scripts to help give people access to Git
- repositories without giving them full access via SSH.
+ HostGitRb allows you to share your Git repositories with other users
+ using SSH Public keys as authentication. You only need one shell account,
+ which makes this great to use in a shared hosting environment, and users
+ won't be able to do anything else other than push/pull to the repositories
+ you define.
END
spec.executables = ['hostgitrb']
- spec.files = FileList['lib/*', 'vendor/*', 'bin/*'] + ['Rakefile', 'README.textile']
+ spec.add_development_dependency('mg')
+ spec.files = Dir['lib/*', 'vendor/*', 'bin/*'] + ['Rakefile', 'README.textile']
spec.homepage = 'http://rfelix.com/'
end
\ No newline at end of file
|
rfelix/hostgitrb
|
7051a6c6d707dfaa1b19ca21ac5ab15bff9c2449
|
Fixed a few formatting issues with only_git.rb output to authorized_keys Added Rakefile for managing the gem
|
diff --git a/Rakefile b/Rakefile
new file mode 100644
index 0000000..b8bfe5e
--- /dev/null
+++ b/Rakefile
@@ -0,0 +1,26 @@
+# ----- Utility Functions -----
+
+def scope(path)
+ File.join(File.dirname(__FILE__), path)
+end
+
+# ----- Packaging -----
+
+require 'rake/gempackagetask'
+load scope('hostgitrb.gemspec')
+
+Rake::GemPackageTask.new(HOSTGITRB_GEMSPEC) do |pkg|
+ if Rake.application.top_level_tasks.include?('release')
+ pkg.need_tar_gz = true
+ pkg.need_tar_bz2 = true
+ pkg.need_zip = true
+ end
+end
+
+desc "Install HostGitRb as a gem."
+task :install => [:package] do
+ sudo = RUBY_PLATFORM =~ /win32|mingw/ ? '' : 'sudo'
+ gem = RUBY_PLATFORM =~ /java/ ? 'jgem' : 'gem'
+ #sh %{#{sudo} #{gem} install --no-ri pkg/hostgitrb-#{File.read(scope('VERSION')).strip}}
+ sh %{#{gem} install --no-ri pkg/hostgitrb-#{File.read(scope('VERSION')).strip}}
+end
\ No newline at end of file
diff --git a/bin/hostgitrb b/bin/hostgitrb
index d29d494..d345fac 100755
--- a/bin/hostgitrb
+++ b/bin/hostgitrb
@@ -1,45 +1,44 @@
#!/usr/bin/env ruby
require 'logger'
require 'ftools'
require File.join(File.dirname(__FILE__), '..', 'vendor', 'trollop.rb')
opts = Trollop.options do
opt :file, 'Set path to public ssh key file', :default => ''
opt :key, 'Provide public ssh key as a string', :default => ''
opt :dir, 'Set full path to directory with git repositories to allow access to', :default => ''
opt :readonly, 'Set access to repositories in --dir to read only', :default => false
opt :nobackup, 'Don\'t make backup of authorized_keys file', :default => false
opt :authorizedkeys, 'Set authorized_keys file', :default => File.expand_path('~/.ssh/authorized_keys')
end
Trollop::die 'Invalid directory' unless File.directory?(opts[:dir])
Trollop::die 'No public ssh key provided' if opts[:key] == '' && !File.exists?(opts[:file])
if File.exists?(opts[:file]) then
ssh_key = File.readlines(opts[:file])[0]
else
ssh_key = opts[:key]
end
if File.exists?(opts[:authorizedkeys]) && !opts[:nobackup] then
backup_file = opts[:authorizedkeys] + '.backup'
count = 2
while(File.exists?(backup_file)) do
backup_file = opts[:authorizedkeys] + ".backup#{count}"
count += 1
end
File.copy(opts[:authorizedkeys], backup_file)
end
-only_git_cmd = File.expand_path(File.join(File.dirname(__FILE__),'only_git.rb')) + " --dir #{opts[:dir]}"
+only_git_cmd = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'only_git.rb')) + " --dir #{opts[:dir]}"
only_git_cmd << " --readonly" if opts[:readonly]
-ssh_inf = "#\n"
+ssh_inf = "\n" if File.exists?(opts[:authorizedkeys]) && File.readlines(opts[:authorizedkeys]).last != "\n"
+ssh_inf << "#\n"
ssh_inf << "# only_git: #{opts[:readonly] ? 'Read-only' : 'R/W'} access to #{opts[:dir]}\n"
ssh_inf << "#\n"
-ssh_cmd = ''
-ssh_cmd = "\n" if File.exists?(opts[:authorizedkeys]) && File.readlines(opts[:authorizedkeys]).last != "\n"
-ssh_cmd << "command=\"#{only_git_cmd}\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty #{ssh_key}"
+ssh_cmd = "command=\"#{only_git_cmd}\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty #{ssh_key}"
File.open(opts[:authorizedkeys], 'a') { |f| f.write(ssh_inf + ssh_cmd) }
\ No newline at end of file
diff --git a/hostgitrb.gemspec b/hostgitrb.gemspec
index dac78fe..e2a2d02 100644
--- a/hostgitrb.gemspec
+++ b/hostgitrb.gemspec
@@ -1,17 +1,18 @@
+# -*- encoding: utf-8 -*-
require 'rubygems'
require 'rake'
HOSTGITRB_GEMSPEC = Gem::Specification.new do |spec|
spec.name = 'hostgitrb'
spec.summary = "Simple Git repository hosting using SSH keys"
spec.version = File.read(File.dirname(__FILE__) + '/VERSION').strip
spec.authors = ['Raoul Felix']
spec.email = '[email protected]'
spec.description = <<-END
This gem contains some simple scripts to help give people access to Git
repositories without giving them full access via SSH.
END
spec.executables = ['hostgitrb']
- spec.files = FileList['lib/*', 'vendor/*', 'bin/*'] + ['README.textile']
+ spec.files = FileList['lib/*', 'vendor/*', 'bin/*'] + ['Rakefile', 'README.textile']
spec.homepage = 'http://rfelix.com/'
end
\ No newline at end of file
|
rfelix/hostgitrb
|
c66094612d601368c4eeac5016b74fc5702c76cb
|
Created gemspec stuff Fixed issue when adding a public key to an authorized_keys file that doesn't exist
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..86339a0
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+*.gem
\ No newline at end of file
diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000..8a9ecc2
--- /dev/null
+++ b/VERSION
@@ -0,0 +1 @@
+0.0.1
\ No newline at end of file
diff --git a/bin/hostgitrb b/bin/hostgitrb
index 2b4e844..d29d494 100755
--- a/bin/hostgitrb
+++ b/bin/hostgitrb
@@ -1,45 +1,45 @@
#!/usr/bin/env ruby
require 'logger'
require 'ftools'
require File.join(File.dirname(__FILE__), '..', 'vendor', 'trollop.rb')
opts = Trollop.options do
opt :file, 'Set path to public ssh key file', :default => ''
opt :key, 'Provide public ssh key as a string', :default => ''
opt :dir, 'Set full path to directory with git repositories to allow access to', :default => ''
opt :readonly, 'Set access to repositories in --dir to read only', :default => false
opt :nobackup, 'Don\'t make backup of authorized_keys file', :default => false
- opt :authorizedkeys, 'Set authorized_keys file', :default => '~/.ssh/authorized_keys'
+ opt :authorizedkeys, 'Set authorized_keys file', :default => File.expand_path('~/.ssh/authorized_keys')
end
Trollop::die 'Invalid directory' unless File.directory?(opts[:dir])
Trollop::die 'No public ssh key provided' if opts[:key] == '' && !File.exists?(opts[:file])
if File.exists?(opts[:file]) then
ssh_key = File.readlines(opts[:file])[0]
else
ssh_key = opts[:key]
end
if File.exists?(opts[:authorizedkeys]) && !opts[:nobackup] then
backup_file = opts[:authorizedkeys] + '.backup'
count = 2
while(File.exists?(backup_file)) do
backup_file = opts[:authorizedkeys] + ".backup#{count}"
count += 1
end
File.copy(opts[:authorizedkeys], backup_file)
end
only_git_cmd = File.expand_path(File.join(File.dirname(__FILE__),'only_git.rb')) + " --dir #{opts[:dir]}"
only_git_cmd << " --readonly" if opts[:readonly]
ssh_inf = "#\n"
ssh_inf << "# only_git: #{opts[:readonly] ? 'Read-only' : 'R/W'} access to #{opts[:dir]}\n"
ssh_inf << "#\n"
ssh_cmd = ''
ssh_cmd = "\n" if File.exists?(opts[:authorizedkeys]) && File.readlines(opts[:authorizedkeys]).last != "\n"
ssh_cmd << "command=\"#{only_git_cmd}\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty #{ssh_key}"
-File.open(opts[:authorizedkeys], 'a+') { |f| f.write(ssh_inf + ssh_cmd) }
\ No newline at end of file
+File.open(opts[:authorizedkeys], 'a') { |f| f.write(ssh_inf + ssh_cmd) }
\ No newline at end of file
diff --git a/hostgitrb.gemspec b/hostgitrb.gemspec
new file mode 100644
index 0000000..dac78fe
--- /dev/null
+++ b/hostgitrb.gemspec
@@ -0,0 +1,17 @@
+require 'rubygems'
+require 'rake'
+
+HOSTGITRB_GEMSPEC = Gem::Specification.new do |spec|
+ spec.name = 'hostgitrb'
+ spec.summary = "Simple Git repository hosting using SSH keys"
+ spec.version = File.read(File.dirname(__FILE__) + '/VERSION').strip
+ spec.authors = ['Raoul Felix']
+ spec.email = '[email protected]'
+ spec.description = <<-END
+ This gem contains some simple scripts to help give people access to Git
+ repositories without giving them full access via SSH.
+ END
+ spec.executables = ['hostgitrb']
+ spec.files = FileList['lib/*', 'vendor/*', 'bin/*'] + ['README.textile']
+ spec.homepage = 'http://rfelix.com/'
+end
\ No newline at end of file
|
rfelix/hostgitrb
|
e77c7812ab784cb2fdb528956b6a2b99e7f7b1b6
|
Rearranged files in directories and changed bash line
|
diff --git a/README.textile b/README.textile
index e773ca5..3f4e8a5 100644
--- a/README.textile
+++ b/README.textile
@@ -1,32 +1,32 @@
h1. HostGitRb
Some simple scripts to help give people access to git repositories without giving them full access via SSH
The directory that contains these scripts should be added to the PATH variable so they can be easily accessed.
h2. only_git.rb
This script is not directly used. It's used by SSH because of the command="" line that is inserted in the ~/.ssh/authorized_keys file.
-Rather than manually adding these entries to the file, the allow_git.rb script can be used.
+Rather than manually adding these entries to the file, the @hostgitrb@ script can be used.
-h2. allow_git.rb
+h2. hostgitrb
Adds the proper SSH command="" lines to the authorized_keys file to give access to other people.
Use the -h argument to see the options.
h2. Example
Imagine I have a directory called /home/user/myrepos that has 2 git repos called one.git and two.git
Now I want to allow a friend of mine to have access to those 2 repos but I don't want him to be able to login via SSH to my server.
So I ask him for his public ssh key, and I execute the command
<pre>./allow_git.rb -d /home/user/myrepos -f /home/user/keys/friend_rsa.pub</pre>
Or the actual key can be passed as an argument, just don't forget the "" because of the spaces:
<pre>./allow_git.rb -d /home/user/myrepos -k "ssh-rsa A.....w== user@host"</pre>
This adds a line to ~/.ssh/authorized_keys and gives him push and pull access to repos one.git and two.git like so:
<pre>git clone [email protected]:one.git
git push origin master
git fetch
git pull
etc.</pre>
\ No newline at end of file
diff --git a/allow_git.rb b/bin/hostgitrb
similarity index 94%
rename from allow_git.rb
rename to bin/hostgitrb
index 01416e6..2b4e844 100755
--- a/allow_git.rb
+++ b/bin/hostgitrb
@@ -1,45 +1,45 @@
-#!/usr/local/bin/ruby
+#!/usr/bin/env ruby
require 'logger'
require 'ftools'
-require File.join(File.dirname(__FILE__), 'libs','trollop.rb')
+require File.join(File.dirname(__FILE__), '..', 'vendor', 'trollop.rb')
opts = Trollop.options do
opt :file, 'Set path to public ssh key file', :default => ''
opt :key, 'Provide public ssh key as a string', :default => ''
opt :dir, 'Set full path to directory with git repositories to allow access to', :default => ''
opt :readonly, 'Set access to repositories in --dir to read only', :default => false
opt :nobackup, 'Don\'t make backup of authorized_keys file', :default => false
opt :authorizedkeys, 'Set authorized_keys file', :default => '~/.ssh/authorized_keys'
end
Trollop::die 'Invalid directory' unless File.directory?(opts[:dir])
Trollop::die 'No public ssh key provided' if opts[:key] == '' && !File.exists?(opts[:file])
if File.exists?(opts[:file]) then
ssh_key = File.readlines(opts[:file])[0]
else
ssh_key = opts[:key]
end
if File.exists?(opts[:authorizedkeys]) && !opts[:nobackup] then
backup_file = opts[:authorizedkeys] + '.backup'
count = 2
while(File.exists?(backup_file)) do
backup_file = opts[:authorizedkeys] + ".backup#{count}"
count += 1
end
File.copy(opts[:authorizedkeys], backup_file)
end
only_git_cmd = File.expand_path(File.join(File.dirname(__FILE__),'only_git.rb')) + " --dir #{opts[:dir]}"
only_git_cmd << " --readonly" if opts[:readonly]
ssh_inf = "#\n"
ssh_inf << "# only_git: #{opts[:readonly] ? 'Read-only' : 'R/W'} access to #{opts[:dir]}\n"
ssh_inf << "#\n"
ssh_cmd = ''
ssh_cmd = "\n" if File.exists?(opts[:authorizedkeys]) && File.readlines(opts[:authorizedkeys]).last != "\n"
ssh_cmd << "command=\"#{only_git_cmd}\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty #{ssh_key}"
File.open(opts[:authorizedkeys], 'a+') { |f| f.write(ssh_inf + ssh_cmd) }
\ No newline at end of file
diff --git a/only_git.rb b/lib/only_git.rb
similarity index 94%
rename from only_git.rb
rename to lib/only_git.rb
index abcfb4b..16095ba 100755
--- a/only_git.rb
+++ b/lib/only_git.rb
@@ -1,42 +1,42 @@
-#!/usr/local/bin/ruby
+#!/usr/bin/env ruby
require 'logger'
-require File.join(File.dirname(__FILE__), 'libs','trollop.rb')
+require File.join(File.dirname(__FILE__), '..', 'vendor', 'trollop.rb')
DEBUG_LEVEL = Logger::ERROR
#Examples of commands that are permitted and that are used by git (git clone/git fetch/git push/git pull)
# git-upload-pack '/home/user/repo/Notes.git'
# git-receive-pack '/home/user/repo/Notes.git'
# git-upload-pack 'Notes.git'
GIT_R_REGEX = /^git[\-](upload)[\-]pack '([a-zA-Z\-_\/]+)([.]git)?'$/
GIT_RW_REGEX = /^git[\-](upload|receive)[\-]pack '([a-zA-Z\-_\/]+)([.]git)?'$/
opts = Trollop::options do
opt :log, "Set log file", :default => File.join(File.dirname(__FILE__), 'debug.log')
opt :dir, "Set directory that contains git repositories", :default => ''
opt :readonly, "Set access to repositories under --dir to read only", :default => false
end
Trollop::die 'Directory with git repositories doesn\'t exist. Needs to be set with --dir' unless File.directory? opts[:dir]
logger = Logger.new(opts[:log], 'weekly')
logger.level = DEBUG_LEVEL
command = String.new(ENV['SSH_ORIGINAL_COMMAND'])
logger.debug("Received command: #{command}")
right_command = GIT_RW_REGEX
right_command = GIT_R_REGEX if opts[:readonly]
logger.debug('Access to repos under dir is set to: ' + (opts[:readonly] ? 'Read' : 'Read/Write'))
if command =~ right_command then
opts[:dir] = File.join(opts[:dir], '')
command.gsub!("-pack '", "-pack '#{opts[:dir]}")
logger.info("Executing command: #{command}")
exec command
else
logger.error("Received bad command")
exec 'echo NOT ALLOWED'
end
diff --git a/libs/trollop.rb b/vendor/trollop.rb
similarity index 100%
rename from libs/trollop.rb
rename to vendor/trollop.rb
|
rfelix/hostgitrb
|
61d370c2d18bbbba061809494a716b8cc858d6ce
|
Fixed up some textile formatting issues in README.textile
|
diff --git a/README.textile b/README.textile
index a84c92f..e773ca5 100644
--- a/README.textile
+++ b/README.textile
@@ -1,38 +1,32 @@
h1. HostGitRb
Some simple scripts to help give people access to git repositories without giving them full access via SSH
The directory that contains these scripts should be added to the PATH variable so they can be easily accessed.
h2. only_git.rb
This script is not directly used. It's used by SSH because of the command="" line that is inserted in the ~/.ssh/authorized_keys file.
Rather than manually adding these entries to the file, the allow_git.rb script can be used.
h2. allow_git.rb
Adds the proper SSH command="" lines to the authorized_keys file to give access to other people.
Use the -h argument to see the options.
h2. Example
Imagine I have a directory called /home/user/myrepos that has 2 git repos called one.git and two.git
Now I want to allow a friend of mine to have access to those 2 repos but I don't want him to be able to login via SSH to my server.
So I ask him for his public ssh key, and I execute the command
-<pre>
- ./allow_git.rb -d /home/user/myrepos -f /home/user/keys/friend_rsa.pub
-</pre>
+<pre>./allow_git.rb -d /home/user/myrepos -f /home/user/keys/friend_rsa.pub</pre>
Or the actual key can be passed as an argument, just don't forget the "" because of the spaces:
-<pre>
- ./allow_git.rb -d /home/user/myrepos -k "ssh-rsa A.....w== user@host"
-</pre>
+<pre>./allow_git.rb -d /home/user/myrepos -k "ssh-rsa A.....w== user@host"</pre>
This adds a line to ~/.ssh/authorized_keys and gives him push and pull access to repos one.git and two.git like so:
-<pre>
- git clone [email protected]:one.git
- git push origin master
- git fetch
- git pull
- etc.
-</pre>
\ No newline at end of file
+<pre>git clone [email protected]:one.git
+git push origin master
+git fetch
+git pull
+etc.</pre>
\ No newline at end of file
|
rfelix/hostgitrb
|
a861299ad689773a89466b2ea0f32e13944d2b0b
|
Converted README to textile
|
diff --git a/README b/README
index 83405ad..a84c92f 100644
--- a/README
+++ b/README
@@ -1,28 +1,38 @@
-= HostGitRb =
+h1. HostGitRb
+
Some simple scripts to help give people access to git repositories without giving them full access via SSH
The directory that contains these scripts should be added to the PATH variable so they can be easily accessed.
-== only_git.rb ==
+h2. only_git.rb
+
This script is not directly used. It's used by SSH because of the command="" line that is inserted in the ~/.ssh/authorized_keys file.
Rather than manually adding these entries to the file, the allow_git.rb script can be used.
-== allow_git.rb ==
+h2. allow_git.rb
+
Adds the proper SSH command="" lines to the authorized_keys file to give access to other people.
Use the -h argument to see the options.
-== Example ==
+h2. Example
+
Imagine I have a directory called /home/user/myrepos that has 2 git repos called one.git and two.git
Now I want to allow a friend of mine to have access to those 2 repos but I don't want him to be able to login via SSH to my server.
So I ask him for his public ssh key, and I execute the command
+<pre>
./allow_git.rb -d /home/user/myrepos -f /home/user/keys/friend_rsa.pub
+</pre>
Or the actual key can be passed as an argument, just don't forget the "" because of the spaces:
+<pre>
./allow_git.rb -d /home/user/myrepos -k "ssh-rsa A.....w== user@host"
+</pre>
This adds a line to ~/.ssh/authorized_keys and gives him push and pull access to repos one.git and two.git like so:
+<pre>
git clone [email protected]:one.git
git push origin master
git fetch
git pull
- etc.
\ No newline at end of file
+ etc.
+</pre>
\ No newline at end of file
|
rfelix/hostgitrb
|
50cbab7e15031488d43ba17ade54d4e831226748
|
allow_git now adds comments to authorized_keys file to make identification easier
|
diff --git a/allow_git.rb b/allow_git.rb
index 4d05dfa..01416e6 100755
--- a/allow_git.rb
+++ b/allow_git.rb
@@ -1,41 +1,45 @@
#!/usr/local/bin/ruby
require 'logger'
require 'ftools'
require File.join(File.dirname(__FILE__), 'libs','trollop.rb')
opts = Trollop.options do
opt :file, 'Set path to public ssh key file', :default => ''
opt :key, 'Provide public ssh key as a string', :default => ''
opt :dir, 'Set full path to directory with git repositories to allow access to', :default => ''
opt :readonly, 'Set access to repositories in --dir to read only', :default => false
opt :nobackup, 'Don\'t make backup of authorized_keys file', :default => false
opt :authorizedkeys, 'Set authorized_keys file', :default => '~/.ssh/authorized_keys'
end
Trollop::die 'Invalid directory' unless File.directory?(opts[:dir])
Trollop::die 'No public ssh key provided' if opts[:key] == '' && !File.exists?(opts[:file])
if File.exists?(opts[:file]) then
ssh_key = File.readlines(opts[:file])[0]
else
ssh_key = opts[:key]
end
if File.exists?(opts[:authorizedkeys]) && !opts[:nobackup] then
backup_file = opts[:authorizedkeys] + '.backup'
count = 2
while(File.exists?(backup_file)) do
backup_file = opts[:authorizedkeys] + ".backup#{count}"
count += 1
end
File.copy(opts[:authorizedkeys], backup_file)
end
only_git_cmd = File.expand_path(File.join(File.dirname(__FILE__),'only_git.rb')) + " --dir #{opts[:dir]}"
only_git_cmd << " --readonly" if opts[:readonly]
-ssh_cmd = ''
-ssh_cmd = "\n" if File.exists?(opts[:authorizedkeys]) && File.readlines(opts[:authorizedkeys]).last != "\n"
+ssh_inf = "#\n"
+ssh_inf << "# only_git: #{opts[:readonly] ? 'Read-only' : 'R/W'} access to #{opts[:dir]}\n"
+ssh_inf << "#\n"
+
+ssh_cmd = ''
+ssh_cmd = "\n" if File.exists?(opts[:authorizedkeys]) && File.readlines(opts[:authorizedkeys]).last != "\n"
ssh_cmd << "command=\"#{only_git_cmd}\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty #{ssh_key}"
-File.open(opts[:authorizedkeys], 'a+') { |f| f.write(ssh_cmd) }
\ No newline at end of file
+File.open(opts[:authorizedkeys], 'a+') { |f| f.write(ssh_inf + ssh_cmd) }
\ No newline at end of file
|
rfelix/hostgitrb
|
651f040501c05e240fc6879bde65669653f4c636
|
Changed Log settings and made the Logger level a constant to be modified when debugging
|
diff --git a/only_git.rb b/only_git.rb
index 7392c54..abcfb4b 100755
--- a/only_git.rb
+++ b/only_git.rb
@@ -1,40 +1,42 @@
#!/usr/local/bin/ruby
require 'logger'
require File.join(File.dirname(__FILE__), 'libs','trollop.rb')
+DEBUG_LEVEL = Logger::ERROR
+
#Examples of commands that are permitted and that are used by git (git clone/git fetch/git push/git pull)
# git-upload-pack '/home/user/repo/Notes.git'
# git-receive-pack '/home/user/repo/Notes.git'
# git-upload-pack 'Notes.git'
GIT_R_REGEX = /^git[\-](upload)[\-]pack '([a-zA-Z\-_\/]+)([.]git)?'$/
GIT_RW_REGEX = /^git[\-](upload|receive)[\-]pack '([a-zA-Z\-_\/]+)([.]git)?'$/
opts = Trollop::options do
opt :log, "Set log file", :default => File.join(File.dirname(__FILE__), 'debug.log')
opt :dir, "Set directory that contains git repositories", :default => ''
opt :readonly, "Set access to repositories under --dir to read only", :default => false
end
Trollop::die 'Directory with git repositories doesn\'t exist. Needs to be set with --dir' unless File.directory? opts[:dir]
-logger = Logger.new(opts[:log])
-logger.level = Logger::DEBUG
+logger = Logger.new(opts[:log], 'weekly')
+logger.level = DEBUG_LEVEL
command = String.new(ENV['SSH_ORIGINAL_COMMAND'])
logger.debug("Received command: #{command}")
right_command = GIT_RW_REGEX
right_command = GIT_R_REGEX if opts[:readonly]
logger.debug('Access to repos under dir is set to: ' + (opts[:readonly] ? 'Read' : 'Read/Write'))
if command =~ right_command then
opts[:dir] = File.join(opts[:dir], '')
command.gsub!("-pack '", "-pack '#{opts[:dir]}")
logger.info("Executing command: #{command}")
exec command
else
- logger.info("Received bad command")
+ logger.error("Received bad command")
exec 'echo NOT ALLOWED'
end
|
rfelix/hostgitrb
|
f427e473af78cdbd1c120be3fe824ed58acc4930
|
Changed regexp to allow / making only_git also permit git urls like ssh://user@domain/gitrepo.git
|
diff --git a/only_git.rb b/only_git.rb
index b662938..7392c54 100755
--- a/only_git.rb
+++ b/only_git.rb
@@ -1,40 +1,40 @@
#!/usr/local/bin/ruby
require 'logger'
require File.join(File.dirname(__FILE__), 'libs','trollop.rb')
#Examples of commands that are permitted and that are used by git (git clone/git fetch/git push/git pull)
# git-upload-pack '/home/user/repo/Notes.git'
# git-receive-pack '/home/user/repo/Notes.git'
# git-upload-pack 'Notes.git'
-GIT_R_REGEX = /^git[\-](upload)[\-]pack '([a-zA-Z\-_]+)([.]git)?'$/
-GIT_RW_REGEX = /^git[\-](upload|receive)[\-]pack '([a-zA-Z\-_]+)([.]git)?'$/
+GIT_R_REGEX = /^git[\-](upload)[\-]pack '([a-zA-Z\-_\/]+)([.]git)?'$/
+GIT_RW_REGEX = /^git[\-](upload|receive)[\-]pack '([a-zA-Z\-_\/]+)([.]git)?'$/
opts = Trollop::options do
opt :log, "Set log file", :default => File.join(File.dirname(__FILE__), 'debug.log')
opt :dir, "Set directory that contains git repositories", :default => ''
opt :readonly, "Set access to repositories under --dir to read only", :default => false
end
Trollop::die 'Directory with git repositories doesn\'t exist. Needs to be set with --dir' unless File.directory? opts[:dir]
logger = Logger.new(opts[:log])
logger.level = Logger::DEBUG
command = String.new(ENV['SSH_ORIGINAL_COMMAND'])
logger.debug("Received command: #{command}")
right_command = GIT_RW_REGEX
right_command = GIT_R_REGEX if opts[:readonly]
logger.debug('Access to repos under dir is set to: ' + (opts[:readonly] ? 'Read' : 'Read/Write'))
if command =~ right_command then
opts[:dir] = File.join(opts[:dir], '')
command.gsub!("-pack '", "-pack '#{opts[:dir]}")
logger.info("Executing command: #{command}")
exec command
else
logger.info("Received bad command")
exec 'echo NOT ALLOWED'
end
|
rfelix/hostgitrb
|
3e520cc37549390fe02a88a7e87e3a2fe0185c43
|
Added some more info and fixed grammar issue
|
diff --git a/README b/README
index 90b9d39..83405ad 100644
--- a/README
+++ b/README
@@ -1,23 +1,28 @@
= HostGitRb =
Some simple scripts to help give people access to git repositories without giving them full access via SSH
-The directory that contains these scripts should be added to the PATH variable so they can easily be accessed.
+The directory that contains these scripts should be added to the PATH variable so they can be easily accessed.
== only_git.rb ==
This script is not directly used. It's used by SSH because of the command="" line that is inserted in the ~/.ssh/authorized_keys file.
Rather than manually adding these entries to the file, the allow_git.rb script can be used.
== allow_git.rb ==
Adds the proper SSH command="" lines to the authorized_keys file to give access to other people.
Use the -h argument to see the options.
== Example ==
Imagine I have a directory called /home/user/myrepos that has 2 git repos called one.git and two.git
Now I want to allow a friend of mine to have access to those 2 repos but I don't want him to be able to login via SSH to my server.
+
So I ask him for his public ssh key, and I execute the command
./allow_git.rb -d /home/user/myrepos -f /home/user/keys/friend_rsa.pub
-Which then adds a line to ~/.ssh/authorized_keys and gives him push and pull access to repos one.git and two.git like so:
+
+Or the actual key can be passed as an argument, just don't forget the "" because of the spaces:
+ ./allow_git.rb -d /home/user/myrepos -k "ssh-rsa A.....w== user@host"
+
+This adds a line to ~/.ssh/authorized_keys and gives him push and pull access to repos one.git and two.git like so:
git clone [email protected]:one.git
git push origin master
git fetch
git pull
etc.
\ No newline at end of file
|
rfelix/hostgitrb
|
7592cfccc01807aca731501815ce9d66333d8b76
|
Changed default log level to DEBUG and fixed problem with frozen string in command
|
diff --git a/only_git.rb b/only_git.rb
index 528028b..34f9786 100755
--- a/only_git.rb
+++ b/only_git.rb
@@ -1,40 +1,40 @@
#!/usr/local/bin/ruby
require 'logger'
require File.join(File.dirname(__FILE__), 'libs','trollop.rb')
#Examples of commands that are permitted and that are used by git (git clone/git fetch/git push/git pull)
# git-upload-pack '/home/rfelixc/gitrepo/cpd/Notes'
# git-receive-pack '/home/rfelixc/gitrepo/cpd/Notes'
# git-upload-pack 'Notes'
GIT_R_REGEX = /^git[\-](upload)[\-]pack '([a-zA-Z\-_]+)([.]git)?'$/
GIT_RW_REGEX = /^git[\-](upload|receive)[\-]pack '([a-zA-Z\-_]+)([.]git)?'$/
opts = Trollop::options do
opt :log, "Set log file", :default => File.join(File.dirname(__FILE__), 'debug.log')
opt :dir, "Set directory that contains git repositories", :default => ''
opt :readonly, "Set access to repositories under --dir to read only", :default => false
end
Trollop::die 'Directory with git repositories doesn\'t exist. Needs to be set with --dir' unless File.directory? opts[:dir]
logger = Logger.new(opts[:log])
-logger.level = Logger::WARN
+logger.level = Logger::DEBUG
-command = ENV['SSH_ORIGINAL_COMMAND']
+command = String.new(ENV['SSH_ORIGINAL_COMMAND'])
logger.debug("Received command: #{command}")
right_command = GIT_RW_REGEX
right_command = GIT_R_REGEX if opts[:readonly]
logger.debug('Access to repos under dir is set to: ' + (opts[:readonly] ? 'Read' : 'Read/Write'))
if command =~ right_command then
opts[:dir] = File.join(opts[:dir], '')
command.gsub!("-pack '", "-pack '#{opts[:dir]}")
logger.info("Executing command: #{command}")
exec command
else
logger.info("Received bad command")
exec 'echo NOT ALLOWED'
end
|
rfelix/hostgitrb
|
98ca0b3319391971eeccb57ac129cb32c7c35817
|
Fixed mistake with Logger level
|
diff --git a/only_git.rb b/only_git.rb
old mode 100644
new mode 100755
index 5520ee5..528028b
--- a/only_git.rb
+++ b/only_git.rb
@@ -1,40 +1,40 @@
#!/usr/local/bin/ruby
require 'logger'
require File.join(File.dirname(__FILE__), 'libs','trollop.rb')
#Examples of commands that are permitted and that are used by git (git clone/git fetch/git push/git pull)
# git-upload-pack '/home/rfelixc/gitrepo/cpd/Notes'
# git-receive-pack '/home/rfelixc/gitrepo/cpd/Notes'
# git-upload-pack 'Notes'
GIT_R_REGEX = /^git[\-](upload)[\-]pack '([a-zA-Z\-_]+)([.]git)?'$/
GIT_RW_REGEX = /^git[\-](upload|receive)[\-]pack '([a-zA-Z\-_]+)([.]git)?'$/
opts = Trollop::options do
opt :log, "Set log file", :default => File.join(File.dirname(__FILE__), 'debug.log')
opt :dir, "Set directory that contains git repositories", :default => ''
opt :readonly, "Set access to repositories under --dir to read only", :default => false
end
Trollop::die 'Directory with git repositories doesn\'t exist. Needs to be set with --dir' unless File.directory? opts[:dir]
logger = Logger.new(opts[:log])
-logger.level = :debug
+logger.level = Logger::WARN
command = ENV['SSH_ORIGINAL_COMMAND']
logger.debug("Received command: #{command}")
right_command = GIT_RW_REGEX
right_command = GIT_R_REGEX if opts[:readonly]
logger.debug('Access to repos under dir is set to: ' + (opts[:readonly] ? 'Read' : 'Read/Write'))
if command =~ right_command then
opts[:dir] = File.join(opts[:dir], '')
command.gsub!("-pack '", "-pack '#{opts[:dir]}")
logger.info("Executing command: #{command}")
exec command
else
logger.info("Received bad command")
exec 'echo NOT ALLOWED'
end
|
rfelix/hostgitrb
|
71f5705743ea786c70339ec84c5a305e318f8093
|
Changed default access to git repos to Read/Write
|
diff --git a/only_git.rb b/only_git.rb
index e34dd19..5520ee5 100644
--- a/only_git.rb
+++ b/only_git.rb
@@ -1,40 +1,40 @@
#!/usr/local/bin/ruby
require 'logger'
require File.join(File.dirname(__FILE__), 'libs','trollop.rb')
#Examples of commands that are permitted and that are used by git (git clone/git fetch/git push/git pull)
# git-upload-pack '/home/rfelixc/gitrepo/cpd/Notes'
# git-receive-pack '/home/rfelixc/gitrepo/cpd/Notes'
# git-upload-pack 'Notes'
GIT_R_REGEX = /^git[\-](upload)[\-]pack '([a-zA-Z\-_]+)([.]git)?'$/
GIT_RW_REGEX = /^git[\-](upload|receive)[\-]pack '([a-zA-Z\-_]+)([.]git)?'$/
opts = Trollop::options do
opt :log, "Set log file", :default => File.join(File.dirname(__FILE__), 'debug.log')
opt :dir, "Set directory that contains git repositories", :default => ''
- opt :readonly, "Set access to repositories under --dir to read only", :default => true
+ opt :readonly, "Set access to repositories under --dir to read only", :default => false
end
Trollop::die 'Directory with git repositories doesn\'t exist. Needs to be set with --dir' unless File.directory? opts[:dir]
logger = Logger.new(opts[:log])
logger.level = :debug
command = ENV['SSH_ORIGINAL_COMMAND']
logger.debug("Received command: #{command}")
right_command = GIT_RW_REGEX
right_command = GIT_R_REGEX if opts[:readonly]
logger.debug('Access to repos under dir is set to: ' + (opts[:readonly] ? 'Read' : 'Read/Write'))
if command =~ right_command then
opts[:dir] = File.join(opts[:dir], '')
command.gsub!("-pack '", "-pack '#{opts[:dir]}")
logger.info("Executing command: #{command}")
exec command
else
logger.info("Received bad command")
exec 'echo NOT ALLOWED'
end
|
rfelix/hostgitrb
|
d426ec48c71f916056cd503658be1de601f90347
|
Added README
|
diff --git a/README b/README
new file mode 100644
index 0000000..db2bc1b
--- /dev/null
+++ b/README
@@ -0,0 +1,3 @@
+HostGitRb
+
+Some simple scripts to help give people access to git repositories without giving them full access via SSH
\ No newline at end of file
|
rfelix/hostgitrb
|
99ca4197aaa5b3c1ec5db3c051509025b60c69c5
|
Added script to limit ssh access to only git
|
diff --git a/libs/trollop.rb b/libs/trollop.rb
new file mode 100644
index 0000000..460c4ce
--- /dev/null
+++ b/libs/trollop.rb
@@ -0,0 +1,714 @@
+## lib/trollop.rb -- trollop command-line processing library
+## Author:: William Morgan (mailto: [email protected])
+## Copyright:: Copyright 2007 William Morgan
+## License:: GNU GPL version 2
+
+module Trollop
+
+VERSION = "1.12"
+
+## Thrown by Parser in the event of a commandline error. Not needed if
+## you're using the Trollop::options entry.
+class CommandlineError < StandardError; end
+
+## Thrown by Parser if the user passes in '-h' or '--help'. Handled
+## automatically by Trollop#options.
+class HelpNeeded < StandardError; end
+
+## Thrown by Parser if the user passes in '-h' or '--version'. Handled
+## automatically by Trollop#options.
+class VersionNeeded < StandardError; end
+
+## Regex for floating point numbers
+FLOAT_RE = /^-?((\d+(\.\d+)?)|(\.\d+))$/
+
+## Regex for parameters
+PARAM_RE = /^-(-|\.$|[^\d\.])/
+
+## The commandline parser. In typical usage, the methods in this class
+## will be handled internally by Trollop::options. In this case, only the
+## #opt, #banner and #version, #depends, and #conflicts methods will
+## typically be called.
+##
+## If it's necessary to instantiate this class (for more complicated
+## argument-parsing situations), be sure to call #parse to actually
+## produce the output hash.
+class Parser
+
+ ## The set of values that indicate a flag option when passed as the
+ ## +:type+ parameter of #opt.
+ FLAG_TYPES = [:flag, :bool, :boolean]
+
+ ## The set of values that indicate a single-parameter option when
+ ## passed as the +:type+ parameter of #opt.
+ ##
+ ## A value of +io+ corresponds to a readable IO resource, including
+ ## a filename, URI, or the strings 'stdin' or '-'.
+ SINGLE_ARG_TYPES = [:int, :integer, :string, :double, :float, :io]
+
+ ## The set of values that indicate a multiple-parameter option when
+ ## passed as the +:type+ parameter of #opt.
+ MULTI_ARG_TYPES = [:ints, :integers, :strings, :doubles, :floats, :ios]
+
+ ## The complete set of legal values for the +:type+ parameter of #opt.
+ TYPES = FLAG_TYPES + SINGLE_ARG_TYPES + MULTI_ARG_TYPES
+
+ INVALID_SHORT_ARG_REGEX = /[\d-]/ #:nodoc:
+
+ ## The values from the commandline that were not interpreted by #parse.
+ attr_reader :leftovers
+
+ ## The complete configuration hashes for each option. (Mainly useful
+ ## for testing.)
+ attr_reader :specs
+
+ ## Initializes the parser, and instance-evaluates any block given.
+ def initialize *a, &b
+ @version = nil
+ @leftovers = []
+ @specs = {}
+ @long = {}
+ @short = {}
+ @order = []
+ @constraints = []
+ @stop_words = []
+ @stop_on_unknown = false
+
+ #instance_eval(&b) if b # can't take arguments
+ cloaker(&b).bind(self).call(*a) if b
+ end
+
+ ## Define an option. +name+ is the option name, a unique identifier
+ ## for the option that you will use internally, which should be a
+ ## symbol or a string. +desc+ is a string description which will be
+ ## displayed in help messages.
+ ##
+ ## Takes the following optional arguments:
+ ##
+ ## [+:long+] Specify the long form of the argument, i.e. the form with two dashes. If unspecified, will be automatically derived based on the argument name by turning the +name+ option into a string, and replacing any _'s by -'s.
+ ## [+:short+] Specify the short form of the argument, i.e. the form with one dash. If unspecified, will be automatically derived from +name+.
+ ## [+:type+] Require that the argument take a parameter or parameters of type +type+. For a single parameter, the value can be a member of +SINGLE_ARG_TYPES+, or a corresponding Ruby class (e.g. +Integer+ for +:int+). For multiple-argument parameters, the value can be any member of +MULTI_ARG_TYPES+ constant. If unset, the default argument type is +:flag+, meaning that the argument does not take a parameter. The specification of +:type+ is not necessary if a +:default+ is given.
+ ## [+:default+] Set the default value for an argument. Without a default value, the hash returned by #parse (and thus Trollop::options) will have a +nil+ value for this key unless the argument is given on the commandline. The argument type is derived automatically from the class of the default value given, so specifying a +:type+ is not necessary if a +:default+ is given. (But see below for an important caveat when +:multi+: is specified too.) If the argument is a flag, and the default is set to +true+, then if it is specified on the the commandline the value will be +false+.
+ ## [+:required+] If set to +true+, the argument must be provided on the commandline.
+ ## [+:multi+] If set to +true+, allows multiple occurrences of the option on the commandline. Otherwise, only a single instance of the option is allowed. (Note that this is different from taking multiple parameters. See below.)
+ ##
+ ## Note that there are two types of argument multiplicity: an argument
+ ## can take multiple values, e.g. "--arg 1 2 3". An argument can also
+ ## be allowed to occur multiple times, e.g. "--arg 1 --arg 2".
+ ##
+ ## Arguments that take multiple values should have a +:type+ parameter
+ ## drawn from +MULTI_ARG_TYPES+ (e.g. +:strings+), or a +:default:+
+ ## value of an array of the correct type (e.g. [String]). The
+ ## value of this argument will be an array of the parameters on the
+ ## commandline.
+ ##
+ ## Arguments that can occur multiple times should be marked with
+ ## +:multi+ => +true+. The value of this argument will also be an array.
+ ##
+ ## These two attributes can be combined (e.g. +:type+ => +:strings+,
+ ## +:multi+ => +true+), in which case the value of the argument will be
+ ## an array of arrays.
+ ##
+ ## There's one ambiguous case to be aware of: when +:multi+: is true and a
+ ## +:default+ is set to an array (of something), it's ambiguous whether this
+ ## is a multi-value argument as well as a multi-occurrence argument.
+ ## In thise case, Trollop assumes that it's not a multi-value argument.
+ ## If you want a multi-value, multi-occurrence argument with a default
+ ## value, you must specify +:type+ as well.
+
+ def opt name, desc="", opts={}
+ raise ArgumentError, "you already have an argument named '#{name}'" if @specs.member? name
+
+ ## fill in :type
+ opts[:type] = # normalize
+ case opts[:type]
+ when :boolean, :bool; :flag
+ when :integer; :int
+ when :integers; :ints
+ when :double; :float
+ when :doubles; :floats
+ when Class
+ case opts[:type].to_s # sigh... there must be a better way to do this
+ when 'TrueClass', 'FalseClass'; :flag
+ when 'String'; :string
+ when 'Integer'; :int
+ when 'Float'; :float
+ when 'IO'; :io
+ else
+ raise ArgumentError, "unsupported argument type '#{opts[:type].class.name}'"
+ end
+ when nil; nil
+ else
+ raise ArgumentError, "unsupported argument type '#{opts[:type]}'" unless TYPES.include?(opts[:type])
+ opts[:type]
+ end
+
+ ## for options with :multi => true, an array default doesn't imply
+ ## a multi-valued argument. for that you have to specify a :type
+ ## as well. (this is how we disambiguate an ambiguous situation;
+ ## see the docs for Parser#opt for details.)
+ disambiguated_default =
+ if opts[:multi] && opts[:default].is_a?(Array) && !opts[:type]
+ opts[:default].first
+ else
+ opts[:default]
+ end
+
+ type_from_default =
+ case disambiguated_default
+ when Integer; :int
+ when Numeric; :float
+ when TrueClass, FalseClass; :flag
+ when String; :string
+ when IO; :io
+ when Array
+ if opts[:default].empty?
+ raise ArgumentError, "multiple argument type cannot be deduced from an empty array for '#{opts[:default][0].class.name}'"
+ end
+ case opts[:default][0] # the first element determines the types
+ when Integer; :ints
+ when Numeric; :floats
+ when String; :strings
+ when IO; :ios
+ else
+ raise ArgumentError, "unsupported multiple argument type '#{opts[:default][0].class.name}'"
+ end
+ when nil; nil
+ else
+ raise ArgumentError, "unsupported argument type '#{opts[:default].class.name}'"
+ end
+
+ raise ArgumentError, ":type specification and default type don't match" if opts[:type] && type_from_default && opts[:type] != type_from_default
+
+ opts[:type] = opts[:type] || type_from_default || :flag
+
+ ## fill in :long
+ opts[:long] = opts[:long] ? opts[:long].to_s : name.to_s.gsub("_", "-")
+ opts[:long] =
+ case opts[:long]
+ when /^--([^-].*)$/
+ $1
+ when /^[^-]/
+ opts[:long]
+ else
+ raise ArgumentError, "invalid long option name #{opts[:long].inspect}"
+ end
+ raise ArgumentError, "long option name #{opts[:long].inspect} is already taken; please specify a (different) :long" if @long[opts[:long]]
+
+ ## fill in :short
+ opts[:short] = opts[:short].to_s if opts[:short] unless opts[:short] == :none
+ opts[:short] = case opts[:short]
+ when /^-(.)$/; $1
+ when nil, :none, /^.$/; opts[:short]
+ else raise ArgumentError, "invalid short option name '#{opts[:short].inspect}'"
+ end
+
+ if opts[:short]
+ raise ArgumentError, "short option name #{opts[:short].inspect} is already taken; please specify a (different) :short" if @short[opts[:short]]
+ raise ArgumentError, "a short option name can't be a number or a dash" if opts[:short] =~ INVALID_SHORT_ARG_REGEX
+ end
+
+ ## fill in :default for flags
+ opts[:default] = false if opts[:type] == :flag && opts[:default].nil?
+
+ ## autobox :default for :multi (multi-occurrence) arguments
+ opts[:default] = [opts[:default]] if opts[:default] && opts[:multi] && !opts[:default].is_a?(Array)
+
+ ## fill in :multi
+ opts[:multi] ||= false
+
+ opts[:desc] ||= desc
+ @long[opts[:long]] = name
+ @short[opts[:short]] = name if opts[:short] && opts[:short] != :none
+ @specs[name] = opts
+ @order << [:opt, name]
+ end
+
+ ## Sets the version string. If set, the user can request the version
+ ## on the commandline. Should probably be of the form "<program name>
+ ## <version number>".
+ def version s=nil; @version = s if s; @version end
+
+ ## Adds text to the help display. Can be interspersed with calls to
+ ## #opt to build a multi-section help page.
+ def banner s; @order << [:text, s] end
+ alias :text :banner
+
+ ## Marks two (or more!) options as requiring each other. Only handles
+ ## undirected (i.e., mutual) dependencies. Directed dependencies are
+ ## better modeled with Trollop::die.
+ def depends *syms
+ syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
+ @constraints << [:depends, syms]
+ end
+
+ ## Marks two (or more!) options as conflicting.
+ def conflicts *syms
+ syms.each { |sym| raise ArgumentError, "unknown option '#{sym}'" unless @specs[sym] }
+ @constraints << [:conflicts, syms]
+ end
+
+ ## Defines a set of words which cause parsing to terminate when
+ ## encountered, such that any options to the left of the word are
+ ## parsed as usual, and options to the right of the word are left
+ ## intact.
+ ##
+ ## A typical use case would be for subcommand support, where these
+ ## would be set to the list of subcommands. A subsequent Trollop
+ ## invocation would then be used to parse subcommand options, after
+ ## shifting the subcommand off of ARGV.
+ def stop_on *words
+ @stop_words = [*words].flatten
+ end
+
+ ## Similar to #stop_on, but stops on any unknown word when encountered
+ ## (unless it is a parameter for an argument). This is useful for
+ ## cases where you don't know the set of subcommands ahead of time,
+ ## i.e., without first parsing the global options.
+ def stop_on_unknown
+ @stop_on_unknown = true
+ end
+
+ ## Parses the commandline. Typically called by Trollop::options.
+ def parse cmdline=ARGV
+ vals = {}
+ required = {}
+
+ opt :version, "Print version and exit" if @version unless @specs[:version] || @long["version"]
+ opt :help, "Show this message" unless @specs[:help] || @long["help"]
+
+ @specs.each do |sym, opts|
+ required[sym] = true if opts[:required]
+ vals[sym] = opts[:default]
+ end
+
+ resolve_default_short_options
+
+ ## resolve symbols
+ given_args = {}
+ @leftovers = each_arg cmdline do |arg, params|
+ sym =
+ case arg
+ when /^-([^-])$/
+ @short[$1]
+ when /^--([^-]\S*)$/
+ @long[$1]
+ else
+ raise CommandlineError, "invalid argument syntax: '#{arg}'"
+ end
+ raise CommandlineError, "unknown argument '#{arg}'" unless sym
+
+ if given_args.include?(sym) && !@specs[sym][:multi]
+ raise CommandlineError, "option '#{arg}' specified multiple times"
+ end
+
+ given_args[sym] ||= {}
+
+ given_args[sym][:arg] = arg
+ given_args[sym][:params] ||= []
+
+ # The block returns the number of parameters taken.
+ num_params_taken = 0
+
+ unless params.nil?
+ if SINGLE_ARG_TYPES.include?(@specs[sym][:type])
+ given_args[sym][:params] << params[0, 1] # take the first parameter
+ num_params_taken = 1
+ elsif MULTI_ARG_TYPES.include?(@specs[sym][:type])
+ given_args[sym][:params] << params # take all the parameters
+ num_params_taken = params.size
+ end
+ end
+
+ num_params_taken
+ end
+
+ ## check for version and help args
+ raise VersionNeeded if given_args.include? :version
+ raise HelpNeeded if given_args.include? :help
+
+ ## check constraint satisfaction
+ @constraints.each do |type, syms|
+ constraint_sym = syms.find { |sym| given_args[sym] }
+ next unless constraint_sym
+
+ case type
+ when :depends
+ syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} requires --#{@specs[sym][:long]}" unless given_args.include? sym }
+ when :conflicts
+ syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} conflicts with --#{@specs[sym][:long]}" if given_args.include?(sym) && (sym != constraint_sym) }
+ end
+ end
+
+ required.each do |sym, val|
+ raise CommandlineError, "option '#{sym}' must be specified" unless given_args.include? sym
+ end
+
+ ## parse parameters
+ given_args.each do |sym, given_data|
+ arg = given_data[:arg]
+ params = given_data[:params]
+
+ opts = @specs[sym]
+ raise CommandlineError, "option '#{arg}' needs a parameter" if params.empty? && opts[:type] != :flag
+
+ vals["#{sym}_given".intern] = true # mark argument as specified on the commandline
+
+ case opts[:type]
+ when :flag
+ vals[sym] = !opts[:default]
+ when :int, :ints
+ vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } }
+ when :float, :floats
+ vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } }
+ when :string, :strings
+ vals[sym] = params.map { |pg| pg.map { |p| p.to_s } }
+ when :io, :ios
+ vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } }
+ end
+
+ if SINGLE_ARG_TYPES.include?(opts[:type])
+ unless opts[:multi] # single parameter
+ vals[sym] = vals[sym][0][0]
+ else # multiple options, each with a single parameter
+ vals[sym] = vals[sym].map { |p| p[0] }
+ end
+ elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi]
+ vals[sym] = vals[sym][0] # single option, with multiple parameters
+ end
+ # else: multiple options, with multiple parameters
+ end
+
+ ## allow openstruct-style accessors
+ class << vals
+ def method_missing(m, *args)
+ self[m] || self[m.to_s]
+ end
+ end
+ vals
+ end
+
+ ## Print the help message to +stream+.
+ def educate stream=$stdout
+ width # just calculate it now; otherwise we have to be careful not to
+ # call this unless the cursor's at the beginning of a line.
+
+ left = {}
+ @specs.each do |name, spec|
+ left[name] = "--#{spec[:long]}" +
+ (spec[:short] && spec[:short] != :none ? ", -#{spec[:short]}" : "") +
+ case spec[:type]
+ when :flag; ""
+ when :int; " <i>"
+ when :ints; " <i+>"
+ when :string; " <s>"
+ when :strings; " <s+>"
+ when :float; " <f>"
+ when :floats; " <f+>"
+ when :io; " <filename/uri>"
+ when :ios; " <filename/uri+>"
+ end
+ end
+
+ leftcol_width = left.values.map { |s| s.length }.max || 0
+ rightcol_start = leftcol_width + 6 # spaces
+
+ unless @order.size > 0 && @order.first.first == :text
+ stream.puts "#@version\n" if @version
+ stream.puts "Options:"
+ end
+
+ @order.each do |what, opt|
+ if what == :text
+ stream.puts wrap(opt)
+ next
+ end
+
+ spec = @specs[opt]
+ stream.printf " %#{leftcol_width}s: ", left[opt]
+ desc = spec[:desc] + begin
+ default_s = case spec[:default]
+ when $stdout; "<stdout>"
+ when $stdin; "<stdin>"
+ when $stderr; "<stderr>"
+ when Array
+ spec[:default].join(", ")
+ else
+ spec[:default].to_s
+ end
+
+ if spec[:default]
+ if spec[:desc] =~ /\.$/
+ " (Default: #{default_s})"
+ else
+ " (default: #{default_s})"
+ end
+ else
+ ""
+ end
+ end
+ stream.puts wrap(desc, :width => width - rightcol_start - 1, :prefix => rightcol_start)
+ end
+ end
+
+ def width #:nodoc:
+ @width ||= if $stdout.tty?
+ begin
+ require 'curses'
+ Curses::init_screen
+ x = Curses::cols
+ Curses::close_screen
+ x
+ rescue Exception
+ 80
+ end
+ else
+ 80
+ end
+ end
+
+ def wrap str, opts={} # :nodoc:
+ if str == ""
+ [""]
+ else
+ str.split("\n").map { |s| wrap_line s, opts }.flatten
+ end
+ end
+
+private
+
+ ## yield successive arg, parameter pairs
+ def each_arg args
+ remains = []
+ i = 0
+
+ until i >= args.length
+ if @stop_words.member? args[i]
+ remains += args[i .. -1]
+ return remains
+ end
+ case args[i]
+ when /^--$/ # arg terminator
+ remains += args[(i + 1) .. -1]
+ return remains
+ when /^--(\S+?)=(\S+)$/ # long argument with equals
+ yield "--#{$1}", [$2]
+ i += 1
+ when /^--(\S+)$/ # long argument
+ params = collect_argument_parameters(args, i + 1)
+ unless params.empty?
+ num_params_taken = yield args[i], params
+ unless num_params_taken
+ if @stop_on_unknown
+ remains += args[i + 1 .. -1]
+ return remains
+ else
+ remains += params
+ end
+ end
+ i += 1 + num_params_taken
+ else # long argument no parameter
+ yield args[i], nil
+ i += 1
+ end
+ when /^-(\S+)$/ # one or more short arguments
+ shortargs = $1.split(//)
+ shortargs.each_with_index do |a, j|
+ if j == (shortargs.length - 1)
+ params = collect_argument_parameters(args, i + 1)
+ unless params.empty?
+ num_params_taken = yield "-#{a}", params
+ unless num_params_taken
+ if @stop_on_unknown
+ remains += args[i + 1 .. -1]
+ return remains
+ else
+ remains += params
+ end
+ end
+ i += 1 + num_params_taken
+ else # argument no parameter
+ yield "-#{a}", nil
+ i += 1
+ end
+ else
+ yield "-#{a}", nil
+ end
+ end
+ else
+ if @stop_on_unknown
+ remains += args[i .. -1]
+ return remains
+ else
+ remains << args[i]
+ i += 1
+ end
+ end
+ end
+
+ remains
+ end
+
+ def parse_integer_parameter param, arg
+ raise CommandlineError, "option '#{arg}' needs an integer" unless param =~ /^\d+$/
+ param.to_i
+ end
+
+ def parse_float_parameter param, arg
+ raise CommandlineError, "option '#{arg}' needs a floating-point number" unless param =~ FLOAT_RE
+ param.to_f
+ end
+
+ def parse_io_parameter param, arg
+ case param
+ when /^(stdin|-)$/i; $stdin
+ else
+ require 'open-uri'
+ begin
+ open param
+ rescue SystemCallError => e
+ raise CommandlineError, "file or url for option '#{arg}' cannot be opened: #{e.message}"
+ end
+ end
+ end
+
+ def collect_argument_parameters args, start_at
+ params = []
+ pos = start_at
+ while args[pos] && args[pos] !~ PARAM_RE && !@stop_words.member?(args[pos]) do
+ params << args[pos]
+ pos += 1
+ end
+ params
+ end
+
+ def resolve_default_short_options
+ @order.each do |type, name|
+ next unless type == :opt
+ opts = @specs[name]
+ next if opts[:short]
+
+ c = opts[:long].split(//).find { |c| c !~ INVALID_SHORT_ARG_REGEX && [email protected]?(c) }
+ raise ArgumentError, "can't generate a default short option name for #{opts[:long].inspect}: out of unique characters" unless c
+
+ opts[:short] = c
+ @short[c] = name
+ end
+ end
+
+ def wrap_line str, opts={}
+ prefix = opts[:prefix] || 0
+ width = opts[:width] || (self.width - 1)
+ start = 0
+ ret = []
+ until start > str.length
+ nextt =
+ if start + width >= str.length
+ str.length
+ else
+ x = str.rindex(/\s/, start + width)
+ x = str.index(/\s/, start) if x && x < start
+ x || str.length
+ end
+ ret << (ret.empty? ? "" : " " * prefix) + str[start ... nextt]
+ start = nextt + 1
+ end
+ ret
+ end
+
+ ## instance_eval but with ability to handle block arguments
+ ## thanks to why: http://redhanded.hobix.com/inspect/aBlockCostume.html
+ def cloaker &b
+ (class << self; self; end).class_eval do
+ define_method :cloaker_, &b
+ meth = instance_method :cloaker_
+ remove_method :cloaker_
+ meth
+ end
+ end
+end
+
+## The top-level entry method into Trollop. Creates a Parser object,
+## passes the block to it, then parses +args+ with it, handling any
+## errors or requests for help or version information appropriately (and
+## then exiting). Modifies +args+ in place. Returns a hash of option
+## values.
+##
+## The block passed in should contain zero or more calls to +opt+
+## (Parser#opt), zero or more calls to +text+ (Parser#text), and
+## probably a call to +version+ (Parser#version).
+##
+## The returned block contains a value for every option specified with
+## +opt+. The value will be the value given on the commandline, or the
+## default value if the option was not specified on the commandline. For
+## every option specified on the commandline, a key "<option
+## name>_given" will also be set in the hash.
+##
+## Example:
+##
+## require 'trollop'
+## opts = Trollop::options do
+## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
+## opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true
+## opt :num_limbs, "Number of limbs", :default => 4 # an integer --num-limbs <i>, defaulting to 4
+## opt :num_thumbs, "Number of thumbs", :type => :int # an integer --num-thumbs <i>, defaulting to nil
+## end
+##
+## ## if called with no arguments
+## p opts # => { :monkey => false, :goat => true, :num_limbs => 4, :num_thumbs => nil }
+##
+## ## if called with --monkey
+## p opts # => {:monkey_given=>true, :monkey=>true, :goat=>true, :num_limbs=>4, :help=>false, :num_thumbs=>nil}
+##
+## See more examples at http://trollop.rubyforge.org.
+def options args = ARGV, *a, &b
+ @p = Parser.new(*a, &b)
+ begin
+ vals = @p.parse args
+ args.clear
+ @p.leftovers.each { |l| args << l }
+ vals
+ rescue CommandlineError => e
+ $stderr.puts "Error: #{e.message}."
+ $stderr.puts "Try --help for help."
+ exit(-1)
+ rescue HelpNeeded
+ @p.educate
+ exit
+ rescue VersionNeeded
+ puts @p.version
+ exit
+ end
+end
+
+## Informs the user that their usage of 'arg' was wrong, as detailed by
+## 'msg', and dies. Example:
+##
+## options do
+## opt :volume, :default => 0.0
+## end
+##
+## die :volume, "too loud" if opts[:volume] > 10.0
+## die :volume, "too soft" if opts[:volume] < 0.1
+##
+## In the one-argument case, simply print that message, a notice
+## about -h, and die. Example:
+##
+## options do
+## opt :whatever # ...
+## end
+##
+## Trollop::die "need at least one filename" if ARGV.empty?
+def die arg, msg=nil
+ if msg
+ $stderr.puts "Error: argument --#{@p.specs[arg][:long]} #{msg}."
+ else
+ $stderr.puts "Error: #{arg}."
+ end
+ $stderr.puts "Try --help for help."
+ exit(-1)
+end
+
+module_function :options, :die
+
+end # module
diff --git a/only_git.rb b/only_git.rb
new file mode 100644
index 0000000..e34dd19
--- /dev/null
+++ b/only_git.rb
@@ -0,0 +1,40 @@
+#!/usr/local/bin/ruby
+
+require 'logger'
+require File.join(File.dirname(__FILE__), 'libs','trollop.rb')
+
+#Examples of commands that are permitted and that are used by git (git clone/git fetch/git push/git pull)
+# git-upload-pack '/home/rfelixc/gitrepo/cpd/Notes'
+# git-receive-pack '/home/rfelixc/gitrepo/cpd/Notes'
+# git-upload-pack 'Notes'
+GIT_R_REGEX = /^git[\-](upload)[\-]pack '([a-zA-Z\-_]+)([.]git)?'$/
+GIT_RW_REGEX = /^git[\-](upload|receive)[\-]pack '([a-zA-Z\-_]+)([.]git)?'$/
+
+opts = Trollop::options do
+ opt :log, "Set log file", :default => File.join(File.dirname(__FILE__), 'debug.log')
+ opt :dir, "Set directory that contains git repositories", :default => ''
+ opt :readonly, "Set access to repositories under --dir to read only", :default => true
+end
+Trollop::die 'Directory with git repositories doesn\'t exist. Needs to be set with --dir' unless File.directory? opts[:dir]
+
+logger = Logger.new(opts[:log])
+logger.level = :debug
+
+command = ENV['SSH_ORIGINAL_COMMAND']
+logger.debug("Received command: #{command}")
+
+right_command = GIT_RW_REGEX
+right_command = GIT_R_REGEX if opts[:readonly]
+logger.debug('Access to repos under dir is set to: ' + (opts[:readonly] ? 'Read' : 'Read/Write'))
+
+if command =~ right_command then
+ opts[:dir] = File.join(opts[:dir], '')
+ command.gsub!("-pack '", "-pack '#{opts[:dir]}")
+ logger.info("Executing command: #{command}")
+ exec command
+else
+ logger.info("Received bad command")
+ exec 'echo NOT ALLOWED'
+end
+
+
|
davethegr8/cakephp-typogrify-helper
|
d26c98899faa378b270eff6c9d56616d390c91c6
|
refotmatted for cakePHP style coding guidelines
|
diff --git a/typogrify.php b/typogrify.php
index a4e1479..4e5b25c 100644
--- a/typogrify.php
+++ b/typogrify.php
@@ -1,1031 +1,1057 @@
<?php
/*
-===============================================================
+======================================================================
CakePHP TypogrifyHelper, based on php-typogrify and PHP SmartyPants
- ================================================================
+======================================================================
Prettifies your web typography by preventing ugly quotes and 'widows'
and providing CSS hooks to style some special cases.
-
-License information follows at the end of this file.
-==============================================================
+======================================================================
CakePHP TypogrifyHelper Copyright (c) 2009, Dave Poole <http://www.zastica.com>
php-typogrify Copyright (c) 2007, Hamish Macpherson
php-typogriphy is a port of the original Python code by Christian Metts.
SmartyPants Copyright (c) 2003-2004 John Gruber <http://daringfireball.net>
PHP SmartyPants Copyright (c) 2004-2005 Michel Fortin <http://www.michelf.com/>
All rights reserved.
+License information follows at the end of this file.
*/
class TypogrifyHelper extends AppHelper {
public $SmartyPantsPHPVersion;
public $SmartyPantsSyntaxVersion;
- public $smartypants_attr;
- public $sp_tags_to_skip;
+ public $smartypantsAttr;
+ public $spTagsToSkip;
/**
* Constructor - Initializes the object and sets up default values
*/
function TypogrifyHelper() {
$this->SmartyPantsPHPVersion = '1.5.1e'; # Fru 9 Dec 2005
$this->SmartyPantsSyntaxVersion = '1.5.1'; # Fri 12 Mar 2004
// Tags to skip:
- $this->sp_tags_to_skip = '<(/?)(?:pre|code|kbd|script|math)[\s>]';
+ $this->spTagsToSkip = '<(/?)(?:pre|code|kbd|script|math)[\s>]';
# Change this to configure.
# 1 => "--" for em-dashes; no en-dash support
# 2 => "---" for em-dashes; "--" for en-dashes
# 3 => "--" for em-dashes; "---" for en-dashes
# See docs for more configuration options.
- $this->smartypants_attr = "1";
+ $this->smartypantsAttr = "1";
}
/**
* Main Typogrify Function. Calls the other functions that process the various
* charactersets
*
* @param $text The text string to Typogrify
* @param $doGuillemets Also process French-style << and >>?
*
* @return The typogrified text
*/
function parse($text, $doGuillemets = false) {
$text = $this->amp( $text );
$text = $this->widont( $text );
$text = $this->smartyPants( $text );
$text = $this->caps( $text );
$text = $this->initial_quotes( $text, $doGuillemets );
$text = $this->dash( $text );
return $this->output($text);
}
/**
* Wraps ampersands in html with ``<span class="amp">`` so they can be
* styled with CSS. Ampersands are also normalized to ``&``. Requires
* ampersands to have whitespace or an `` `` on both sides.
*
* It won't mess up & that are already wrapped, in entities or URLs
*
* @param $text Text to transform ampersands in
*
* @return The string with ampersands replaced
*/
- function amp( $text ) {
- $amp_finder = "/(\s| )(&|&|&\#38;|&)(\s| )/";
- return preg_replace($amp_finder, '\\1<span class="amp">&</span>\\3', $text);
+ function amp ($text) {
+ $ampFinder = "/(\s| )(&|&|&\#38;|&)(\s| )/";
+ return preg_replace($ampFinder, '\\1<span class="amp">&</span>\\3', $text);
}
/**
* Replaces the space between the last two words in a string with `` ``
* Works in these block tags ``(h1-h6, p, li)`` and also accounts for
* potential closing inline elements ``a, em, strong, span, b, i``
*
* Empty HTMLs shouldn't error
*
* @param $text Text to transform
*
* @return The string with widows (hopefully) eliminated
*/
- function widont( $text ) {
+ function widont ($text) {
$tags = "a|span|i|b|em|strong|acronym|caps|sub|sup|abbr|big|small|code|cite|tt";
// This regex is a beast, tread lightly
- $widont_finder = "/([^\s])\s+(((<($tags)[^>]*>)*\s*[^\s<>]+)(<\/($tags)>)*[^\s<>]*\s*(<\/(p|h[1-6]|li)>|$))/i";
+ $widontFinder = "/([^\s])\s+(((<($tags)[^>]*>)*\s*[^\s<>]+)(<\/($tags)>)*[^\s<>]*\s*(<\/(p|h[1-6]|li)>|$))/i";
- return preg_replace($widont_finder, '$1 $2', $text);
+ return preg_replace($widontFinder, '$1 $2', $text);
}
/**
* Puts a   before and after an &ndash or —
* Dashes may have whitespace or an `` `` on both sides
*
* @param $text Text to transform
*
* @return The string with dashes padded with  
*/
- function dash( $text ) {
- $dash_finder = "/(\s| | )*(—|–|–|–|—|—)(\s| | )*/";
- return preg_replace($dash_finder, ' \\2 ', $text);
+ function dash ($text) {
+ $dashFinder = "/(\s| | )*(—|–|–|–|—|—)(\s| | )*/";
+ return preg_replace($dashFinder, ' \\2 ', $text);
}
/**
* Wraps multiple capital letters in ``<span class="caps">``
* so they can be styled with CSS.
*
* Uses the smartypants tokenizer to not screw with HTML or with tags it shouldn't.
*
* @param $text Text to transform
*
* @return The string with caps wrapped
*/
- function caps( $text ) {
+ function caps ($text) {
$tokens = $this->TokenizeHTML($text);
$result = array();
- $in_skipped_tag = false;
+ $inSkippedTag = false;
- $cap_finder = "/(
+ $capFinder = "/(
(\b[A-Z\d]* # Group 2: Any amount of caps and digits
[A-Z]\d*[A-Z] # A cap string much at least include two caps (but they can have digits between them)
[A-Z\d]*\b) # Any amount of caps and digits
| (\b[A-Z]+\.\s? # OR: Group 3: Some caps, followed by a '.' and an optional space
(?:[A-Z]+\.\s?)+) # Followed by the same thing at least once more
(?:\s|\b|$))/x";
- $tags_to_skip_regex = "/<(\/)?(?:pre|code|kbd|script|math)[^>]*>/i";
+ $tagsToSkipRegex = "/<(\/)?(?:pre|code|kbd|script|math)[^>]*>/i";
foreach ($tokens as $token) {
if ( $token[0] == "tag" ) {
// Don't mess with tags.
$result[] = $token[1];
- $close_match = preg_match($tags_to_skip_regex, $token[1]);
+ $closeMatch = preg_match($tagsToSkipRegex, $token[1]);
- if ( $close_match ) {
- $in_skipped_tag = true;
+ if ($closeMatch) {
+ $inSkippedTag = true;
}
else {
- $in_skipped_tag = false;
+ $inSkippedTag = false;
}
}
else {
- if ( $in_skipped_tag ) {
+ if ($inSkippedTag) {
$result[] = $token[1];
}
else {
- $result[] = preg_replace_callback($cap_finder, array('typogrifyhelper', '_cap_wrapper'), $token[1]);
+ $result[] = preg_replace_callback($capFinder, array('typogrifyhelper', '__capWrapper'), $token[1]);
}
}
- }
- return join("", $result);
+ }
+
+ return implode("", $result);
}
/**
* This is necessary to keep dotted cap strings to pick up extra spaces
* used in preg_replace_callback in caps()
*
- * @param $matchobj The function that called this one
+ * @param $matchObj The function that called this one
*
* @return A formatted string
*/
- function _cap_wrapper( $matchobj ) {
- if ( !empty($matchobj[2]) ) {
- return sprintf('<span class="caps">%s</span>', $matchobj[2]);
+ function __capWrapper ($matchObj) {
+ if (!empty($matchObj[2])) {
+ return sprintf('<span class="caps">%s</span>', $matchObj[2]);
}
else {
- $mthree = $matchobj[3];
- if ( ($mthree{strlen($mthree)-1}) == " " ) {
- $caps = substr($mthree, 0, -1);
+ $mThree = $matchObj[3];
+ if (($mThree{strlen($mThree)-1}) == " ") {
+ $caps = substr($mThree, 0, -1);
$tail = ' ';
}
else {
- $caps = $mthree;
+ $caps = $mThree;
$tail = '';
}
return sprintf('<span class="caps">%s</span>%s', $caps, $tail);
}
}
/**
* initial_quotes
*
* Wraps initial quotes in ``class="dquo"`` for double quotes or
* ``class="quo"`` for single quotes. Works in these block tags ``(h1-h6, p, li)``
* and also accounts for potential opening inline elements ``a, em, strong, span, b, i``
* Optionally choose to apply quote span tags to Gullemets as well.
*
* @param $text The string to format initial quotes
* @param $doGuillemets Also do << and >>?
*
* @return The text string with initial quotes wrapped with class="dquo" or class="quo"
*/
- function initial_quotes( $text, $doGuillemets = false ) {
- $quote_finder = "/((<(p|h[1-6]|li)[^>]*>|^) # start with an opening p, h1-6, li or the start of the string
- \s* # optional white space!
- (<(a|em|span|strong|i|b)[^>]*>\s*)*) # optional opening inline tags, with more optional white space for each.
- ((\"|“|&\#8220;)|('|‘|&\#8216;)) # Find me a quote! (only need to find the left quotes and the primes)
- # double quotes are in group 7, singles in group 8
- /ix";
+ function initial_quotes ($text, $doGuillemets = false) {
+ /*
+ - start with an opening p, h1-6, li or the start of the string
+ - optional white space
+ - optional opening inline tags, with more optional white space for each.
+ - Find me a quote! (only need to find the left quotes and the primes)
+ - double quotes are in group 7, singles in group 8
+ */
+
+ $quoteFinder = "/((<(p|h[1-6]|li)[^>]*>|^)\s*(<(a|em|span|strong|i|b)[^>]*>\s*)*)((\"|“|&\#8220;)|('|‘|&\#8216;))/ix";
if ($doGuillemets) {
- $quote_finder = "/((<(p|h[1-6]|li)[^>]*>|^) # start with an opening p, h1-6, li or the start of the string
- \s* # optional white space!
- (<(a|em|span|strong|i|b)[^>]*>\s*)*) # optional opening inline tags, with more optional white space for each.
- ((\"|“|&\#8220;|\xAE|&\#171;|«)|('|‘|&\#8216;)) # Find me a quote! (only need to find the left quotes and the primes) - also look for guillemets (>> and << characters))
- # double quotes are in group 7, singles in group 8
- /ix";
+ /*
+ - start with an opening p, h1-6, li or the start of the string
+ - optional white space!
+ - optional opening inline tags, with more optional white space for each.
+ - Find me a quote! (only need to find the left quotes and the primes) - also look for guillemets (>> and << characters))
+ - double quotes are in group 7, singles in group 8
+ */
+ $quoteFinder = "/((<(p|h[1-6]|li)[^>]*>|^)\s*(<(a|em|span|strong|i|b)[^>]*>\s*)*)((\"|“|&\#8220;|\xAE|&\#171;|«)|('|‘|&\#8216;))/ix";
}
- return preg_replace_callback($quote_finder, array('typogrifyhelper', '_quote_wrapper'), $text);
+ return preg_replace_callback($quoteFinder, array('typogrifyhelper', '__quoteWrapper'), $text);
}
/**
* This is necessary to keep quote string formatted properly
*
- * @param $matchobj The function that called this one
+ * @param $matchObj The function that called this one
*
* @return A formatted string
*/
- function _quote_wrapper( $matchobj ) {
- if ( !empty($matchobj[7]) ) {
+ function __quoteWrapper ($matchObj) {
+ if ( !empty($matchObj[7]) ) {
$classname = "dquo";
- $quote = $matchobj[7];
+ $quote = $matchObj[7];
}
else {
$classname = "quo";
- $quote = $matchobj[8];
+ $quote = $matchObj[8];
}
- return sprintf('%s<span class="%s">%s</span>', $matchobj[1], $classname, $quote);
+ return sprintf('%s<span class="%s">%s</span>', $matchObj[1], $classname, $quote);
}
-
- //SmartyPants fuctions follow
/**
* The main SmartyPants function. Calls the other formatters
*
* @param $text The text to format
* @param $attr (Optional) Overridden attribute setting, for applying different formatting
*
* @return The formatted text, looking pretty
*/
function smartyPants($text, $attr = NULL) {
- # Paramaters:
- $text; # text to be parsed
- $attr; # value of the smart_quotes="" attribute
-
- if ($attr == NULL) $attr = $this->smartypants_attr;
+ if ($attr == NULL) {
+ $attr = $this->smartypantsAttr;
+ }
- # Options to specify which transformations to make:
- $do_stupefy = FALSE;
- $convert_quot = 0; # should we translate " entities into normal quotes?
+ // Options to specify which transformations to make:
+ $doStupefy = FALSE;
+ $convertQuot = 0; # should we translate " entities into normal quotes?
# Parse attributes:
# 0 : do nothing
# 1 : set all
# 2 : set all, using old school en- and em- dash shortcuts
# 3 : set all, using inverted old school en and em- dash shortcuts
#
# q : quotes
# b : backtick quotes (``double'' only)
# B : backtick quotes (``double'' and `single')
# d : dashes
# D : old school dashes
# i : inverted old school dashes
# e : ellipses
# w : convert " entities to " for Dreamweaver users
if ($attr == "0") {
# Do nothing.
return $text;
}
else if ($attr == "1") {
# Do everything, turn all options on.
- $do_quotes = 1;
- $do_backticks = 1;
- $do_dashes = 1;
- $do_ellipses = 1;
+ $doQuotes = 1;
+ $doBackticks = 1;
+ $doDashes = 1;
+ $doEllipses = 1;
}
else if ($attr == "2") {
# Do everything, turn all options on, use old school dash shorthand.
- $do_quotes = 1;
- $do_backticks = 1;
- $do_dashes = 2;
- $do_ellipses = 1;
+ $doQuotes = 1;
+ $doBackticks = 1;
+ $doDashes = 2;
+ $doEllipses = 1;
}
else if ($attr == "3") {
# Do everything, turn all options on, use inverted old school dash shorthand.
- $do_quotes = 1;
- $do_backticks = 1;
- $do_dashes = 3;
- $do_ellipses = 1;
+ $doQuotes = 1;
+ $doBackticks = 1;
+ $doDashes = 3;
+ $doEllipses = 1;
}
else if ($attr == "-1") {
# Special "stupefy" mode.
- $do_stupefy = 1;
+ $doStupefy = 1;
}
else {
$chars = preg_split('//', $attr);
foreach ($chars as $c){
- if ($c == "q") { $do_quotes = 1; }
- else if ($c == "b") { $do_backticks = 1; }
- else if ($c == "B") { $do_backticks = 2; }
- else if ($c == "d") { $do_dashes = 1; }
- else if ($c == "D") { $do_dashes = 2; }
- else if ($c == "i") { $do_dashes = 3; }
- else if ($c == "e") { $do_ellipses = 1; }
- else if ($c == "w") { $convert_quot = 1; }
+ if ($c == "q") {
+ $doQuotes = 1;
+ }
+ elseif ($c == "b") {
+ $doBackticks = 1;
+ }
+ elseif ($c == "B") {
+ $doBackticks = 2;
+ }
+ elseif ($c == "d") {
+ $doDashes = 1;
+ }
+ elseif ($c == "D") {
+ $doDashes = 2;
+ }
+ elseif ($c == "i") {
+ $doDashes= 3;
+ }
+ elseif ($c == "e") {
+ $doEllipses = 1;
+ }
+ elseif ($c == "w") {
+ $convertQuot = 1;
+ }
else {
# Unknown attribute option, ignore.
}
}
}
$tokens = $this->TokenizeHTML($text);
$result = '';
- $in_pre = 0; # Keep track of when we're inside <pre> or <code> tags.
-
- $prev_token_last_char = ""; # This is a cheat, used to get some context
- # for one-character tokens that consist of
- # just a quote char. What we do is remember
- # the last character of the previous text
- # token, to use as context to curl single-
- # character quote tokens correctly.
-
- foreach ($tokens as $cur_token) {
- if ($cur_token[0] == "tag") {
- # Don't mess with quotes inside tags.
- $result .= $cur_token[1];
- if (preg_match("@$this->sp_tags_to_skip@", $cur_token[1], $matches)) {
- $in_pre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
+ $inPre = 0; // Keep track of when we're inside <pre> or <code> tags.
+
+ /* $prevTokenLastChar is a cheat, used to get some context
+ for one-character tokens that consist of
+ just a quote char. What we do is remember
+ the last character of the previous text
+ token, to use as context to curl single-
+ character quote tokens correctly. */
+ $prevTokenLastChar = "";
+
+ foreach ($tokens as $currentToken) {
+ if ($currentToken[0] == "tag") {
+ // Don't mess with quotes inside tags.
+ $result .= $currentToken[1];
+ if (preg_match("@$this->spTagsToSkip@", $currentToken[1], $matches)) {
+ $inPre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
}
}
else {
- $t = $cur_token[1];
- $last_char = substr($t, -1); # Remember last char of this token before processing.
- if (! $in_pre) {
- $t = $this->ProcessEscapes($t);
+ $t = $currentToken[1];
+ $lastChar = substr($t, -1); // Remember last char of this token before processing.
+ if (! $inPre) {
+ $t = $this->processEscapes($t);
- if ($convert_quot) {
+ if ($convertQuot) {
$t = preg_replace('/"/', '"', $t);
}
- if ($do_dashes) {
- if ($do_dashes == 1) $t = $this->EducateDashes($t);
- if ($do_dashes == 2) $t = $this->EducateDashesOldSchool($t);
- if ($do_dashes == 3) $t = $this->EducateDashesOldSchoolInverted($t);
+ if ($doDashes) {
+ if ($doDashes == 1) {
+ $t = $this->educateDashes($t);
+ }
+ if ($doDashes == 2) {
+ $t = $this->educateDashesOldSchool($t);
+ }
+ if ($doDashes == 3) {
+ $t = $this->educateDashesOldSchoolInverted($t);
+ }
}
- if ($do_ellipses) $t = $this->EducateEllipses($t);
+ if ($doEllipses) $t = $this->educateEllipses($t);
- # Note: backticks need to be processed before quotes.
- if ($do_backticks) {
+ // Note: backticks need to be processed before quotes.
+ if ($doBackticks) {
$t = $this->educateBackticks($t);
- if ($do_backticks == 2) $t = $this->EducateSingleBackticks($t);
+ if ($doBackticks == 2) $t = $this->educateSingleBackticks($t);
}
- if ($do_quotes) {
+ if ($doQuotes) {
if ($t == "'") {
# Special case: single-character ' token
- if (preg_match('/\S/', $prev_token_last_char)) {
+ if (preg_match('/\S/', $prevTokenLastChar)) {
$t = "’";
}
else {
$t = "‘";
}
}
- else if ($t == '"') {
+ elseif ($t == '"') {
# Special case: single-character " token
- if (preg_match('/\S/', $prev_token_last_char)) {
+ if (preg_match('/\S/', $prevTokenLastChar)) {
$t = "”";
}
else {
$t = "“";
}
}
else {
# Normal case:
$t = $this->educateQuotes($t);
}
}
- if ($do_stupefy) $t = $this->StupefyEntities($t);
+ if ($doStupefy) {
+ $t = $this->stupefyEntities($t);
+ }
}
- $prev_token_last_char = $last_char;
+ $prevTokenLastChar = $lastChar;
$result .= $t;
}
}
return $result;
}
/**
* SmartQuotes function. Unused?
*
* @param $text Text to parse
* @param $attr Attribute processing flag
*
* @return Processed text
*/
function smartQuotes($text, $attr = NULL) {
- # Paramaters:
- $text; # text to be parsed
- $attr; # value of the smart_quotes="" attribute
- if ($attr == NULL) $attr = $this->smartypants_attr;
+ if ($attr == NULL) {
+ $attr = $this->smartypantsAttr;
+ }
- $do_backticks; # should we educate ``backticks'' -style quotes?
+ $doBackticks; // should we educate ``backticks'' -style quotes?
if ($attr == 0) {
- # do nothing;
+ // do nothing;
return $text;
}
else if ($attr == 2) {
- # smarten ``backticks'' -style quotes
- $do_backticks = 1;
+ // smarten ``backticks'' -style quotes
+ $doBackticks = 1;
}
else {
- $do_backticks = 0;
+ $doBackticks = 0;
}
- # Special case to handle quotes at the very end of $text when preceded by
- # an HTML tag. Add a space to give the quote education algorithm a bit of
- # context, so that it can guess correctly that it's a closing quote:
- $add_extra_space = 0;
+ /* Special case to handle quotes at the very end of $text when preceded by
+ an HTML tag. Add a space to give the quote education algorithm a bit of
+ context, so that it can guess correctly that it's a closing quote: */
+ $addExtraSpace = 0;
if (preg_match("/>['\"]\\z/", $text)) {
- $add_extra_space = 1; # Remember, so we can trim the extra space later.
+ $addExtraSpace = 1; # Remember, so we can trim the extra space later.
$text .= " ";
}
$tokens = $this->TokenizeHTML($text);
$result = '';
- $in_pre = 0; # Keep track of when we're inside <pre> or <code> tags
-
- $prev_token_last_char = ""; # This is a cheat, used to get some context
- # for one-character tokens that consist of
- # just a quote char. What we do is remember
- # the last character of the previous text
- # token, to use as context to curl single-
- # character quote tokens correctly.
-
- foreach ($tokens as $cur_token) {
- if ($cur_token[0] == "tag") {
+ $inPre = 0; # Keep track of when we're inside <pre> or <code> tags
+
+ /* $prevTokenLastChar is a cheat, used to get some context
+ for one-character tokens that consist of
+ just a quote char. What we do is remember
+ the last character of the previous text
+ token, to use as context to curl single-
+ character quote tokens correctly. */
+ $prevTokenLastChar = "";
+
+ foreach ($tokens as $currentToken) {
+ if ($currentToken[0] == "tag") {
# Don't mess with quotes inside tags
- $result .= $cur_token[1];
- if (preg_match("@$this->sp_tags_to_skip@", $cur_token[1], $matches)) {
- $in_pre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
+ $result .= $currentToken[1];
+ if (preg_match("@$this->spTagsToSkip@", $currentToken[1], $matches)) {
+ $inPre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
}
}
else {
- $t = $cur_token[1];
- $last_char = substr($t, -1); # Remember last char of this token before processing.
- if (! $in_pre) {
- $t = $this->ProcessEscapes($t);
- if ($do_backticks) {
+ $t = $currentToken[1];
+ $lastChar = substr($t, -1); // Remember last char of this token before processing.
+ if (! $inPre) {
+ $t = $this->processEscapes($t);
+ if ($doBackticks) {
$t = $this->educateBackticks($t);
}
if ($t == "'") {
- # Special case: single-character ' token
- if (preg_match('/\S/', $prev_token_last_char)) {
+ // Special case: single-character ' token
+ if (preg_match('/\S/', $prevTokenLastChar)) {
$t = "’";
}
else {
$t = "‘";
}
}
- else if ($t == '"') {
- # Special case: single-character " token
- if (preg_match('/\S/', $prev_token_last_char)) {
+ elseif ($t == '"') {
+ // Special case: single-character " token
+ if (preg_match('/\S/', $prevTokenLastChar)) {
$t = "”";
}
else {
$t = "“";
}
}
else {
# Normal case:
$t = $this->educateQuotes($t);
}
}
- $prev_token_last_char = $last_char;
+ $prevTokenLastChar = $lastChar;
$result .= $t;
}
}
- if ($add_extra_space) {
+ if ($addExtraSpace) {
preg_replace('/ \z/', '', $result); # Trim trailing space if we added one earlier.
}
return $result;
}
/**
* Replaces dashes with proper em and en dashes. Unused?
*
* @param $text The text to parse
* @param $attr The flag to what kind of processing we're doing.
*
* @return The processed text
*/
function smartDashes($text, $attr = NULL) {
+ if ($attr == NULL) {
+ $attr = $this->smartypantsAttr;
+ }
- # Paramaters:
- $text; # text to be parsed
- $attr; # value of the smart_dashes="" attribute
- if ($attr == NULL) $attr = $this->smartypants_attr;
-
- # reference to the subroutine to use for dash education, default to EducateDashes:
- $dash_sub_ref = 'EducateDashes';
+ # reference to the subroutine to use for dash education, default to educateDashes:
+ $dashSubRef = 'educateDashes';
if ($attr == 0) {
# do nothing;
return $text;
}
else if ($attr == 2) {
# use old smart dash shortcuts, "--" for en, "---" for em
- $dash_sub_ref = 'EducateDashesOldSchool';
+ $dashSubRef = 'educateDashesOldSchool';
}
else if ($attr == 3) {
# inverse of 2, "--" for em, "---" for en
- $dash_sub_ref = 'EducateDashesOldSchoolInverted';
+ $dashSubRef = 'educateDashesOldSchoolInverted';
}
$tokens;
$tokens = $this->TokenizeHTML($text);
$result = '';
- $in_pre = 0; # Keep track of when we're inside <pre> or <code> tags
- foreach ($tokens as $cur_token) {
- if ($cur_token[0] == "tag") {
+ $inPre = 0; # Keep track of when we're inside <pre> or <code> tags
+ foreach ($tokens as $currentToken) {
+ if ($currentToken[0] == "tag") {
# Don't mess with quotes inside tags
- $result .= $cur_token[1];
- if (preg_match("@$this->sp_tags_to_skip@", $cur_token[1], $matches)) {
- $in_pre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
+ $result .= $currentToken[1];
+ if (preg_match("@$this->spTagsToSkip@", $currentToken[1], $matches)) {
+ $inPre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
}
} else {
- $t = $cur_token[1];
- if (! $in_pre) {
- $t = $this->ProcessEscapes($t);
- $t = $dash_sub_ref($t);
+ $t = $currentToken[1];
+ if (! $inPre) {
+ $t = $this->processEscapes($t);
+ $t = $dashSubRef($t);
}
$result .= $t;
}
}
return $result;
}
/**
* Replaces ... or . . . with proper … Unused?
*
* @param $text The text to parse
* @param $attr The flag to what kind of processing we're doing.
*
* @return The processed text
*/
function smartEllipses($text, $attr = NULL) {
- # Paramaters:
- $text; # text to be parsed
- $attr; # value of the smart_ellipses="" attribute
- if ($attr == NULL) $attr = $this->smartypants_attr;
+ if ($attr == NULL) {
+ $attr = $this->smartypantsAttr;
+ }
if ($attr == 0) {
# do nothing;
return $text;
}
-
- $tokens;
+
$tokens = $this->TokenizeHTML($text);
$result = '';
- $in_pre = 0; # Keep track of when we're inside <pre> or <code> tags
- foreach ($tokens as $cur_token) {
- if ($cur_token[0] == "tag") {
+ $inPre = 0; # Keep track of when we're inside <pre> or <code> tags
+ foreach ($tokens as $currentToken) {
+ if ($currentToken[0] == "tag") {
# Don't mess with quotes inside tags
- $result .= $cur_token[1];
- if (preg_match("@$this->sp_tags_to_skip@", $cur_token[1], $matches)) {
- $in_pre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
+ $result .= $currentToken[1];
+ if (preg_match("@$this->spTagsToSkip@", $currentToken[1], $matches)) {
+ $inPre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
}
} else {
- $t = $cur_token[1];
- if (! $in_pre) {
- $t = $this->ProcessEscapes($t);
- $t = $this->EducateEllipses($t);
+ $t = $currentToken[1];
+ if (! $inPre) {
+ $t = $this->processEscapes($t);
+ $t = $this->educateEllipses($t);
}
$result .= $t;
}
}
return $result;
}
/**
* Process quotes into HTML entities
*
* Example input: "Isn't this fun?"
* Example output: “Isn’t this fun?”
*
- * @param $_ String to process
+ * @param $str String to process
*
* @return The string, with "educated" curly quote HTML entities.
*/
- function educateQuotes($_) {
+ function educateQuotes($str) {
# Make our own "punctuation" character class, because the POSIX-style
# [:PUNCT:] is only available in Perl 5.6 or later:
- $punct_class = "[!\"#\\$\\%'()*+,-.\\/:;<=>?\\@\\[\\\\\]\\^_`{|}~]";
+ $punctuationClass = "[!\"#\\$\\%'()*+,-.\\/:;<=>?\\@\\[\\\\\]\\^_`{|}~]";
# Special case if the very first character is a quote
# followed by punctuation at a non-word-break. Close the quotes by brute force:
- $_ = preg_replace(
- array("/^'(?=$punct_class\\B)/", "/^\"(?=$punct_class\\B)/"),
- array('’', '”'), $_);
+ $str = preg_replace(
+ array("/^'(?=$punctuationClass\\B)/", "/^\"(?=$punctuationClass\\B)/"),
+ array('’', '”'), $str);
# Special case for double sets of quotes, e.g.:
# <p>He said, "'Quoted' words in a larger quote."</p>
- $_ = preg_replace(
+ $str = preg_replace(
array("/\"'(?=\w)/", "/'\"(?=\w)/"),
- array('“‘', '‘“'), $_);
+ array('“‘', '‘“'), $str);
# Special case for decade abbreviations (the '80s):
- $_ = preg_replace("/'(?=\\d{2}s)/", '’', $_);
-
- $close_class = '[^\ \t\r\n\[\{\(\-]';
- $dec_dashes = '&\#8211;|&\#8212;';
-
- # Get most opening single quotes:
- $_ = preg_replace("{
- (
- \\s | # a whitespace char, or
- | # a non-breaking space entity, or
- -- | # dashes, or
- &[mn]dash; | # named dash entities
- $dec_dashes | # or decimal entities
- &\\#x201[34]; # or hex
- )
- ' # the quote
- (?=\\w) # followed by a word character
- }x", '\1‘', $_);
- # Single closing quotes:
- $_ = preg_replace("{
- ($close_class)?
- '
- (?(1)| # If $1 captured, then do nothing;
- (?=\\s | s\\b) # otherwise, positive lookahead for a whitespace
- ) # char or an 's' at a word ending position. This
- # is a special case to handle something like:
- # \"<i>Custer</i>'s Last Stand.\"
- }xi", '\1’', $_);
-
- # Any remaining single quotes should be opening ones:
- $_ = str_replace("'", '‘', $_);
-
-
- # Get most opening double quotes:
- $_ = preg_replace("{
- (
- \\s | # a whitespace char, or
- | # a non-breaking space entity, or
- -- | # dashes, or
- &[mn]dash; | # named dash entities
- $dec_dashes | # or decimal entities
- &\\#x201[34]; # or hex
- )
- \" # the quote
- (?=\\w) # followed by a word character
- }x", '\1“', $_);
-
- # Double closing quotes:
- $_ = preg_replace("{
- ($close_class)?
- \"
- (?(1)|(?=\\s)) # If $1 captured, then do nothing;
- # if not, then make sure the next char is whitespace.
- }x", '\1”', $_);
-
- # Any remaining quotes should be opening ones.
- $_ = str_replace('"', '“', $_);
-
- return $_;
+ $str = preg_replace("/'(?=\\d{2}s)/", '’', $str);
+
+ $closeClass = '[^\ \t\r\n\[\{\(\-]';
+ $decDashes = '&\#8211;|&\#8212;';
+
+ // Get most opening single quotes:
+ /*
+ (
+ a whitespace char, or
+ anon-breaking space entity, or
+ dashes, or
+ named dash entities
+ or decimal entities
+ or hex
+ )
+ the quote
+ followed by a word character
+ */
+ $str = preg_replace("{(\\s| |--|&[mn]dash;|$decDashes|&\\#x201[34];)'(?=\\w)}x", '\1‘', $str);
+
+ // Single closing quotes:
+ /*
+ If $1 captured, then do nothing;
+ otherwise, positive lookahead for a whitespace
+ char or an 's' at a word ending position. This
+ is a special case to handle something like:
+ \"<i>Custer</i>'s Last Stand.\"
+ */
+ $str = preg_replace("{($closeClass)?'(?(1)|(?=\\s | s\\b))}xi", '\1’', $str);
+
+ // Any remaining single quotes should be opening ones:
+ $str = str_replace("'", '‘', $str);
+
+ /* Get most opening double quotes:
+ a whitespace char, or
+ a non-breaking space entity, or
+ dashes, or
+ named dash entities
+ or decimal entities
+ or hex
+
+ the quote
+ followed by a word character
+ */
+ $str = preg_replace("{(\\s| |--|&[mn]dash;|$decDashes|&\\#x201[34];)\"(?=\\w)}x", '\1“', $str);
+
+ /* Double closing quotes:
+
+ If $1 captured, then do nothing;
+ if not, then make sure the next char is whitespace.
+ */
+ $str = preg_replace("{($closeClass)?\"(?(1)|(?=\\s))}x", '\1”', $str);
+
+ //Any remaining quotes should be opening ones.
+ $str = str_replace('"', '“', $str);
+
+ return $str;
}
/**
* Process backticks-style doublequotes translated into proper HTML entities
* Example input: ``Isn't this fun?''
* Example output: “Isn't this fun?”
*
- * @param $_ The string to convert backticks in
+ * @param $str The string to convert backticks in
*
* @return The processed string
*/
- function educateBackticks($_) {
+ function educateBackticks($str) {
- $_ = str_replace(array("``", "''",),
- array('“', '”'), $_);
- return $_;
+ $str = str_replace(array("``", "''",),
+ array('“', '”'), $str);
+ return $str;
}
/**
* Formats string with `backticks' -style single quotes
* translated into HTML curly quote entities.
* Example input: `Isn't this fun?'
* Example output: ‘Isn’t this fun?’
*
- * @param $_ The string to process
+ * @param $str The string to process
*
* @return The processed string
*/
- function EducateSingleBackticks($_) {
- $_ = str_replace(array("`", "'",),
- array('‘', '’'), $_);
- return $_;
+ function educateSingleBackticks($str) {
+ $str = str_replace(array("`", "'",),
+ array('‘', '’'), $str);
+ return $str;
}
/**
* Processes a string with each instance of "--" translated to
* an em-dash HTML entity.
*
- * @param $_ The strong to process
+ * @param $str The strong to process
*
* @return The processed string
*
*/
- function EducateDashes($_) {
- $_ = str_replace('--', '—', $_);
- return $_;
+ function educateDashes($str) {
+ $str = str_replace('--', '—', $str);
+ return $str;
}
/**
* Processes a string with each instance of "--" translated to
* an en-dash HTML entity, and each "---" translated to
* an em-dash HTML entity.
*
- * @param $_ The string to process
+ * @param $str The string to process
*
* @return The processed string
*/
- function EducateDashesOldSchool($_) {
+ function educateDashesOldSchool($str) {
// em en
- $_ = str_replace(array("---", "--",),
- array('—', '–'), $_);
- return $_;
+ $str = str_replace(array("---", "--",),
+ array('—', '–'), $str);
+ return $str;
}
/**
* Processes a string, with each instance of "--" translated to
* an em-dash HTML entity, and each "---" translated to
* an en-dash HTML entity. Two reasons why: First, unlike the
* en- and em-dash syntax supported by
- * EducateDashesOldSchool(), it's compatible with existing
+ * educateDashesOldSchool(), it's compatible with existing
* entries written before SmartyPants 1.1, back when "--" was
* only used for em-dashes. Second, em-dashes are more
* common than en-dashes, and so it sort of makes sense that
* the shortcut should be shorter to type. (Thanks to Aaron
* Swartz for the idea.)
*
- * @param $_ The string to process
+ * @param $str The string to process
*
* @return The processed string
*/
- function EducateDashesOldSchoolInverted($_) {
+ function educateDashesOldSchoolInverted($str) {
// en em
- $_ = str_replace(array("---", "--",),
- array('–', '—'), $_);
- return $_;
+ $str = str_replace(array("---", "--",),
+ array('–', '—'), $str);
+ return $str;
}
/**
* Processes a string with each instance of "..." translated to
* an ellipsis HTML entity. Also converts the case where
* there are spaces between the dots.
*
* Example input: Huh...?
* Example output: Huh…?
*
- * @param $_ The string to process
+ * @param $str The string to process
*
* @return The processed string
*/
- function EducateEllipses($_) {
- $_ = str_replace(array("...", ". . .",), '…', $_);
- return $_;
+ function educateEllipses($str) {
+ $str = str_replace(array("...", ". . .",), '…', $str);
+ return $str;
}
/**
* Processes a string, with each SmartyPants HTML entity translated to
* its ASCII counterpart.
*
* Example input: “Hello — world.”
* Example output: "Hello -- world."
*
- * @param $_ The string to process
+ * @param $str The string to process
*
* @return The processed string
*/
- function StupefyEntities($_) {
+ function stupefyEntities($str) {
// en-dash em-dash
- $_ = str_replace(array('–', '—'),
- array('-', '--'), $_);
+ $str = str_replace(array('–', '—'),
+ array('-', '--'), $str);
// single quote open close
- $_ = str_replace(array('‘', '’'), "'", $_);
+ $str = str_replace(array('‘', '’'), "'", $str);
// double quote open close
- $_ = str_replace(array('“', '”'), '"', $_);
+ $str = str_replace(array('“', '”'), '"', $str);
- $_ = str_replace('…', '...', $_); // ellipsis
+ $str = str_replace('…', '...', $str); // ellipsis
- return $_;
+ return $str;
}
/**
* Processes a string, with after processing the following backslash
* escape sequences. This is useful if you want to force a "dumb"
* quote or other character to appear.
*
* Escape Value
* ------ -----
* \\ \
* \" "
* \' '
* \. .
* \- -
* \` `
*
- * @param $_ The string to process.
+ * @param $str The string to process.
*
* @return The processed string
*/
- function ProcessEscapes($_) {
- $_ = str_replace(
+ function processEscapes($str) {
+ $str = str_replace(
array('\\\\', '\"', "\'", '\.', '\-', '\`'),
- array('\', '"', ''', '.', '-', '`'), $_);
+ array('\', '"', ''', '.', '-', '`'), $str);
- return $_;
+ return $str;
}
/**
* Processes a string, and transforms it into an array of the tokens comprising the input
* string. Each token is either a tag (possibly with nested,
* tags contained therein, such as <a href="<MTFoo>">, or a
* run of text between tags. Each element of the array is a
* two-element array; the first is either 'tag' or 'text';
* the second is the actual value.
*
* Regular expression derived from the _tokenize() subroutine in
* Brad Choate's MTRegex plugin.
* <http://www.bradchoate.com/past/mtregex.php>
*
* @param $str String containing HTML markup.
*
* @return The tokenized array
*/
function TokenizeHTML($str) {
$index = 0;
$tokens = array();
- $match = '(?s:<!(?:--.*?--\s*)+>)|'. # comment
- '(?s:<\?.*?\?>)|'. # processing instruction
- # regular tags
+ /*
+ comment
+ processing instruction
+ regular tags
+ */
+ $match = '(?s:<!(?:--.*?--\s*)+>)|'.
+ '(?s:<\?.*?\?>)|'.
'(?:<[/!$]?[-a-zA-Z0-9:]+\b(?>[^"\'>]+|"[^"]*"|\'[^\']*\')*>)';
$parts = preg_split("{($match)}", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($parts as $part) {
- if (++$index % 2 && $part != '')
+ if (++$index % 2 && $part != '') {
$tokens[] = array('text', $part);
- else
+ }
+ else {
$tokens[] = array('tag', $part);
+ }
}
return $tokens;
}
}
/*
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the php-typogrify nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
* Neither the name "SmartyPants" nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
* Neither the name "CakePHP TypogrifyHelper" nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=============
php-typogrify
=============
Announcement:
<http://www2.jeffcroft.com/sidenotes/2007/may/29/typogrify-easily-produce-web-typography-doesnt-suc/>
Example Page:
<http://static.mintchaos.com/projects/typogrify/>
Project Page:
<http://code.google.com/p/typogrify/>
PHP SmartyPants
<http://www.michelf.com/projects/php-smartypants/>
===============
PHP SmartyPants
===============
Smart punctuation for web sites
by John Gruber
<http://daringfireball.net>
PHP port by Michel Fortin
<http://www.michelf.com/>
Copyright (c) 2003-2004 John Gruber
Copyright (c) 2004-2005 Michel Fortin
Description
-----------
This is a PHP translation of the original SmartyPants quote educator written in
Perl by John Gruber.
SmartyPants is a web publishing utility that translates plain ASCII
punctuation characters into "smart" typographic punctuation HTML
entities. SmartyPants can perform the following transformations:
* Straight quotes (`"` and `'`) into "curly" quote HTML entities
* Backticks-style quotes (` ``like this'' `) into "curly" quote HTML
entities
* Dashes (`--` and `---`) into en- and em-dash entities
* Three consecutive dots (`...`) into an ellipsis entity
SmartyPants does not modify characters within `<pre>`, `<code>`, `<kbd>`,
`<script>`, or `<math>` tag blocks. Typically, these tags are used to
display text where smart quotes and other "smart punctuation" would not
be appropriate, such as source code or example markup.
### Backslash Escapes ###
If you need to use literal straight quotes (or plain hyphens and
periods), SmartyPants accepts the following backslash escape sequences
to force non-smart punctuation. It does so by transforming the escape
sequence into a decimal-encoded HTML entity:
Escape Value Character
------ ----- ---------
\\ \ \
\" " "
\' ' '
\. . .
\- - -
\` ` `
This is useful, for example, when you want to use straight quotes as
foot and inch marks: 6'2" tall; a 17" iMac.
### Algorithmic Shortcomings ###
One situation in which quotes will get curled the wrong way is when
apostrophes are used at the start of leading contractions. For example:
'Twas the night before Christmas.
In the case above, SmartyPants will turn the apostrophe into an opening
single-quote, when in fact it should be a closing one. I don't think
this problem can be solved in the general case -- every word processor
I've tried gets this wrong as well. In such cases, it's best to use the
proper HTML entity for closing single-quotes (`’`) by hand.
Author
------
John Gruber
<http://daringfireball.net/>
Ported to PHP by Michel Fortin
<http://www.michelf.com/>
Additional Credits
------------------
Portions of this plug-in are based on Brad Choate's nifty MTRegex plug-in.
Brad Choate also contributed a few bits of source code to this plug-in.
Brad Choate is a fine hacker indeed. (<http://bradchoate.com/>)
Jeremy Hedley (<http://antipixel.com/>) and Charles Wiltgen
(<http://playbacktime.com/>) deserve mention for exemplary beta testing.
*/
?>
\ No newline at end of file
|
davethegr8/cakephp-typogrify-helper
|
8498ae352142d91102ba68c03d4995c550725a4f
|
Changed to PHPDoc style documentation
|
diff --git a/typogrify.php b/typogrify.php
index 73b4e12..a4e1479 100644
--- a/typogrify.php
+++ b/typogrify.php
@@ -1,1041 +1,1031 @@
<?php
/*
===============================================================
CakePHP TypogrifyHelper, based on php-typogrify and PHP SmartyPants
================================================================
Prettifies your web typography by preventing ugly quotes and 'widows'
and providing CSS hooks to style some special cases.
License information follows at the end of this file.
==============================================================
CakePHP TypogrifyHelper Copyright (c) 2009, Dave Poole <http://www.zastica.com>
php-typogrify Copyright (c) 2007, Hamish Macpherson
+
php-typogriphy is a port of the original Python code by Christian Metts.
SmartyPants Copyright (c) 2003-2004 John Gruber <http://daringfireball.net>
PHP SmartyPants Copyright (c) 2004-2005 Michel Fortin <http://www.michelf.com/>
All rights reserved.
*/
class TypogrifyHelper extends AppHelper {
public $SmartyPantsPHPVersion;
public $SmartyPantsSyntaxVersion;
public $smartypants_attr;
public $sp_tags_to_skip;
+ /**
+ * Constructor - Initializes the object and sets up default values
+ */
function TypogrifyHelper() {
$this->SmartyPantsPHPVersion = '1.5.1e'; # Fru 9 Dec 2005
$this->SmartyPantsSyntaxVersion = '1.5.1'; # Fri 12 Mar 2004
-
- # Configurable variables:
- $this->smartypants_attr = "1"; # Change this to configure.
- # 1 => "--" for em-dashes; no en-dash support
- # 2 => "---" for em-dashes; "--" for en-dashes
- # 3 => "--" for em-dashes; "---" for en-dashes
- # See docs for more configuration options.
-
- # Globals:
+ // Tags to skip:
$this->sp_tags_to_skip = '<(/?)(?:pre|code|kbd|script|math)[\s>]';
+
+ # Change this to configure.
+ # 1 => "--" for em-dashes; no en-dash support
+ # 2 => "---" for em-dashes; "--" for en-dashes
+ # 3 => "--" for em-dashes; "---" for en-dashes
+ # See docs for more configuration options.
+ $this->smartypants_attr = "1";
}
- /* Main Typogrify Function */
- function parse($text, $do_guillemets = false) {
+ /**
+ * Main Typogrify Function. Calls the other functions that process the various
+ * charactersets
+ *
+ * @param $text The text string to Typogrify
+ * @param $doGuillemets Also process French-style << and >>?
+ *
+ * @return The typogrified text
+ */
+ function parse($text, $doGuillemets = false) {
$text = $this->amp( $text );
$text = $this->widont( $text );
- $text = $this->SmartyPants( $text );
+ $text = $this->smartyPants( $text );
$text = $this->caps( $text );
- $text = $this->initial_quotes( $text, $do_guillemets );
+ $text = $this->initial_quotes( $text, $doGuillemets );
$text = $this->dash( $text );
return $this->output($text);
}
/**
- * amp
- *
* Wraps ampersands in html with ``<span class="amp">`` so they can be
* styled with CSS. Ampersands are also normalized to ``&``. Requires
* ampersands to have whitespace or an `` `` on both sides.
*
* It won't mess up & that are already wrapped, in entities or URLs
+ *
+ * @param $text Text to transform ampersands in
+ *
+ * @return The string with ampersands replaced
*/
- function amp( $text )
- {
+ function amp( $text ) {
$amp_finder = "/(\s| )(&|&|&\#38;|&)(\s| )/";
return preg_replace($amp_finder, '\\1<span class="amp">&</span>\\3', $text);
}
/**
- * widont
- *
* Replaces the space between the last two words in a string with `` ``
* Works in these block tags ``(h1-h6, p, li)`` and also accounts for
* potential closing inline elements ``a, em, strong, span, b, i``
*
* Empty HTMLs shouldn't error
+ *
+ * @param $text Text to transform
+ *
+ * @return The string with widows (hopefully) eliminated
*/
- function widont( $text )
- {
+ function widont( $text ) {
+ $tags = "a|span|i|b|em|strong|acronym|caps|sub|sup|abbr|big|small|code|cite|tt";
+
// This regex is a beast, tread lightly
- $widont_finder = "/([^\s])\s+(((<(a|span|i|b|em|strong|acronym|caps|sub|sup|abbr|big|small|code|cite|tt)[^>]*>)*\s*[^\s<>]+)(<\/(a|span|i|b|em|strong|acronym|caps|sub|sup|abbr|big|small|code|cite|tt)>)*[^\s<>]*\s*(<\/(p|h[1-6]|li)>|$))/i";
+ $widont_finder = "/([^\s])\s+(((<($tags)[^>]*>)*\s*[^\s<>]+)(<\/($tags)>)*[^\s<>]*\s*(<\/(p|h[1-6]|li)>|$))/i";
return preg_replace($widont_finder, '$1 $2', $text);
}
/**
- * dash
- *
* Puts a   before and after an &ndash or —
* Dashes may have whitespace or an `` `` on both sides
+ *
+ * @param $text Text to transform
+ *
+ * @return The string with dashes padded with  
*/
- function dash( $text )
- {
+ function dash( $text ) {
$dash_finder = "/(\s| | )*(—|–|–|–|—|—)(\s| | )*/";
return preg_replace($dash_finder, ' \\2 ', $text);
}
/**
- * caps
- *
* Wraps multiple capital letters in ``<span class="caps">``
* so they can be styled with CSS.
*
* Uses the smartypants tokenizer to not screw with HTML or with tags it shouldn't.
+ *
+ * @param $text Text to transform
+ *
+ * @return The string with caps wrapped
*/
- function caps( $text )
- {
- // Tokenize; see smartypants.php
+ function caps( $text ) {
$tokens = $this->TokenizeHTML($text);
$result = array();
$in_skipped_tag = false;
$cap_finder = "/(
(\b[A-Z\d]* # Group 2: Any amount of caps and digits
[A-Z]\d*[A-Z] # A cap string much at least include two caps (but they can have digits between them)
[A-Z\d]*\b) # Any amount of caps and digits
| (\b[A-Z]+\.\s? # OR: Group 3: Some caps, followed by a '.' and an optional space
(?:[A-Z]+\.\s?)+) # Followed by the same thing at least once more
(?:\s|\b|$))/x";
$tags_to_skip_regex = "/<(\/)?(?:pre|code|kbd|script|math)[^>]*>/i";
- foreach ($tokens as $token)
- {
- if ( $token[0] == "tag" )
- {
+ foreach ($tokens as $token) {
+ if ( $token[0] == "tag" ) {
// Don't mess with tags.
$result[] = $token[1];
$close_match = preg_match($tags_to_skip_regex, $token[1]);
- if ( $close_match )
- {
+
+ if ( $close_match ) {
$in_skipped_tag = true;
}
- else
- {
+ else {
$in_skipped_tag = false;
}
}
- else
- {
- if ( $in_skipped_tag )
- {
+ else {
+ if ( $in_skipped_tag ) {
$result[] = $token[1];
}
- else
- {
+ else {
$result[] = preg_replace_callback($cap_finder, array('typogrifyhelper', '_cap_wrapper'), $token[1]);
}
}
}
return join("", $result);
}
/**
* This is necessary to keep dotted cap strings to pick up extra spaces
- * used in preg_replace_callback later on
+ * used in preg_replace_callback in caps()
+ *
+ * @param $matchobj The function that called this one
+ *
+ * @return A formatted string
*/
- function _cap_wrapper( $matchobj )
- {
- if ( !empty($matchobj[2]) )
- {
+ function _cap_wrapper( $matchobj ) {
+ if ( !empty($matchobj[2]) ) {
return sprintf('<span class="caps">%s</span>', $matchobj[2]);
}
- else
- {
+ else {
$mthree = $matchobj[3];
- if ( ($mthree{strlen($mthree)-1}) == " " )
- {
+ if ( ($mthree{strlen($mthree)-1}) == " " ) {
$caps = substr($mthree, 0, -1);
$tail = ' ';
}
- else
- {
+ else {
$caps = $mthree;
$tail = '';
}
return sprintf('<span class="caps">%s</span>%s', $caps, $tail);
}
}
-
/**
* initial_quotes
*
* Wraps initial quotes in ``class="dquo"`` for double quotes or
* ``class="quo"`` for single quotes. Works in these block tags ``(h1-h6, p, li)``
* and also accounts for potential opening inline elements ``a, em, strong, span, b, i``
* Optionally choose to apply quote span tags to Gullemets as well.
+ *
+ * @param $text The string to format initial quotes
+ * @param $doGuillemets Also do << and >>?
+ *
+ * @return The text string with initial quotes wrapped with class="dquo" or class="quo"
*/
- function initial_quotes( $text, $do_guillemets = false )
- {
+ function initial_quotes( $text, $doGuillemets = false ) {
$quote_finder = "/((<(p|h[1-6]|li)[^>]*>|^) # start with an opening p, h1-6, li or the start of the string
\s* # optional white space!
(<(a|em|span|strong|i|b)[^>]*>\s*)*) # optional opening inline tags, with more optional white space for each.
((\"|“|&\#8220;)|('|‘|&\#8216;)) # Find me a quote! (only need to find the left quotes and the primes)
# double quotes are in group 7, singles in group 8
/ix";
- if ($do_guillemets)
- {
+ if ($doGuillemets) {
$quote_finder = "/((<(p|h[1-6]|li)[^>]*>|^) # start with an opening p, h1-6, li or the start of the string
\s* # optional white space!
(<(a|em|span|strong|i|b)[^>]*>\s*)*) # optional opening inline tags, with more optional white space for each.
((\"|“|&\#8220;|\xAE|&\#171;|«)|('|‘|&\#8216;)) # Find me a quote! (only need to find the left quotes and the primes) - also look for guillemets (>> and << characters))
# double quotes are in group 7, singles in group 8
/ix";
}
return preg_replace_callback($quote_finder, array('typogrifyhelper', '_quote_wrapper'), $text);
}
-
- function _quote_wrapper( $matchobj )
- {
- if ( !empty($matchobj[7]) )
- {
+ /**
+ * This is necessary to keep quote string formatted properly
+ *
+ * @param $matchobj The function that called this one
+ *
+ * @return A formatted string
+ */
+ function _quote_wrapper( $matchobj ) {
+ if ( !empty($matchobj[7]) ) {
$classname = "dquo";
$quote = $matchobj[7];
}
- else
- {
+ else {
$classname = "quo";
$quote = $matchobj[8];
}
return sprintf('%s<span class="%s">%s</span>', $matchobj[1], $classname, $quote);
}
- //SmartyPants fuctions
+ //SmartyPants fuctions follow
- function SmartyPants($text, $attr = NULL, $ctx = NULL) {
+ /**
+ * The main SmartyPants function. Calls the other formatters
+ *
+ * @param $text The text to format
+ * @param $attr (Optional) Overridden attribute setting, for applying different formatting
+ *
+ * @return The formatted text, looking pretty
+ */
+ function smartyPants($text, $attr = NULL) {
# Paramaters:
$text; # text to be parsed
$attr; # value of the smart_quotes="" attribute
- $ctx; # MT context object (unused)
+
if ($attr == NULL) $attr = $this->smartypants_attr;
# Options to specify which transformations to make:
$do_stupefy = FALSE;
$convert_quot = 0; # should we translate " entities into normal quotes?
# Parse attributes:
# 0 : do nothing
# 1 : set all
# 2 : set all, using old school en- and em- dash shortcuts
# 3 : set all, using inverted old school en and em- dash shortcuts
#
# q : quotes
# b : backtick quotes (``double'' only)
# B : backtick quotes (``double'' and `single')
# d : dashes
# D : old school dashes
# i : inverted old school dashes
# e : ellipses
# w : convert " entities to " for Dreamweaver users
if ($attr == "0") {
# Do nothing.
return $text;
}
else if ($attr == "1") {
# Do everything, turn all options on.
$do_quotes = 1;
$do_backticks = 1;
$do_dashes = 1;
$do_ellipses = 1;
}
else if ($attr == "2") {
# Do everything, turn all options on, use old school dash shorthand.
$do_quotes = 1;
$do_backticks = 1;
$do_dashes = 2;
$do_ellipses = 1;
}
else if ($attr == "3") {
# Do everything, turn all options on, use inverted old school dash shorthand.
$do_quotes = 1;
$do_backticks = 1;
$do_dashes = 3;
$do_ellipses = 1;
}
else if ($attr == "-1") {
# Special "stupefy" mode.
$do_stupefy = 1;
}
else {
$chars = preg_split('//', $attr);
foreach ($chars as $c){
if ($c == "q") { $do_quotes = 1; }
else if ($c == "b") { $do_backticks = 1; }
else if ($c == "B") { $do_backticks = 2; }
else if ($c == "d") { $do_dashes = 1; }
else if ($c == "D") { $do_dashes = 2; }
else if ($c == "i") { $do_dashes = 3; }
else if ($c == "e") { $do_ellipses = 1; }
else if ($c == "w") { $convert_quot = 1; }
else {
# Unknown attribute option, ignore.
}
}
}
$tokens = $this->TokenizeHTML($text);
$result = '';
$in_pre = 0; # Keep track of when we're inside <pre> or <code> tags.
$prev_token_last_char = ""; # This is a cheat, used to get some context
# for one-character tokens that consist of
# just a quote char. What we do is remember
# the last character of the previous text
# token, to use as context to curl single-
# character quote tokens correctly.
foreach ($tokens as $cur_token) {
if ($cur_token[0] == "tag") {
# Don't mess with quotes inside tags.
$result .= $cur_token[1];
if (preg_match("@$this->sp_tags_to_skip@", $cur_token[1], $matches)) {
$in_pre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
}
- } else {
+ }
+ else {
$t = $cur_token[1];
$last_char = substr($t, -1); # Remember last char of this token before processing.
if (! $in_pre) {
$t = $this->ProcessEscapes($t);
if ($convert_quot) {
$t = preg_replace('/"/', '"', $t);
}
if ($do_dashes) {
if ($do_dashes == 1) $t = $this->EducateDashes($t);
if ($do_dashes == 2) $t = $this->EducateDashesOldSchool($t);
if ($do_dashes == 3) $t = $this->EducateDashesOldSchoolInverted($t);
}
if ($do_ellipses) $t = $this->EducateEllipses($t);
# Note: backticks need to be processed before quotes.
if ($do_backticks) {
- $t = $this->EducateBackticks($t);
+ $t = $this->educateBackticks($t);
if ($do_backticks == 2) $t = $this->EducateSingleBackticks($t);
}
if ($do_quotes) {
if ($t == "'") {
# Special case: single-character ' token
if (preg_match('/\S/', $prev_token_last_char)) {
$t = "’";
}
else {
$t = "‘";
}
}
else if ($t == '"') {
# Special case: single-character " token
if (preg_match('/\S/', $prev_token_last_char)) {
$t = "”";
}
else {
$t = "“";
}
}
else {
# Normal case:
- $t = $this->EducateQuotes($t);
+ $t = $this->educateQuotes($t);
}
}
if ($do_stupefy) $t = $this->StupefyEntities($t);
}
$prev_token_last_char = $last_char;
$result .= $t;
}
}
return $result;
}
-
- function SmartQuotes($text, $attr = NULL, $ctx = NULL) {
+ /**
+ * SmartQuotes function. Unused?
+ *
+ * @param $text Text to parse
+ * @param $attr Attribute processing flag
+ *
+ * @return Processed text
+ */
+ function smartQuotes($text, $attr = NULL) {
# Paramaters:
$text; # text to be parsed
$attr; # value of the smart_quotes="" attribute
- $ctx; # MT context object (unused)
if ($attr == NULL) $attr = $this->smartypants_attr;
$do_backticks; # should we educate ``backticks'' -style quotes?
if ($attr == 0) {
# do nothing;
return $text;
}
else if ($attr == 2) {
# smarten ``backticks'' -style quotes
$do_backticks = 1;
}
else {
$do_backticks = 0;
}
# Special case to handle quotes at the very end of $text when preceded by
# an HTML tag. Add a space to give the quote education algorithm a bit of
# context, so that it can guess correctly that it's a closing quote:
$add_extra_space = 0;
if (preg_match("/>['\"]\\z/", $text)) {
$add_extra_space = 1; # Remember, so we can trim the extra space later.
$text .= " ";
}
$tokens = $this->TokenizeHTML($text);
$result = '';
$in_pre = 0; # Keep track of when we're inside <pre> or <code> tags
$prev_token_last_char = ""; # This is a cheat, used to get some context
# for one-character tokens that consist of
# just a quote char. What we do is remember
# the last character of the previous text
# token, to use as context to curl single-
# character quote tokens correctly.
foreach ($tokens as $cur_token) {
if ($cur_token[0] == "tag") {
# Don't mess with quotes inside tags
$result .= $cur_token[1];
if (preg_match("@$this->sp_tags_to_skip@", $cur_token[1], $matches)) {
$in_pre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
}
- } else {
+ }
+ else {
$t = $cur_token[1];
$last_char = substr($t, -1); # Remember last char of this token before processing.
if (! $in_pre) {
$t = $this->ProcessEscapes($t);
if ($do_backticks) {
- $t = $this->EducateBackticks($t);
+ $t = $this->educateBackticks($t);
}
if ($t == "'") {
# Special case: single-character ' token
if (preg_match('/\S/', $prev_token_last_char)) {
$t = "’";
}
else {
$t = "‘";
}
}
else if ($t == '"') {
# Special case: single-character " token
if (preg_match('/\S/', $prev_token_last_char)) {
$t = "”";
}
else {
$t = "“";
}
}
else {
# Normal case:
- $t = $this->EducateQuotes($t);
+ $t = $this->educateQuotes($t);
}
}
$prev_token_last_char = $last_char;
$result .= $t;
}
}
if ($add_extra_space) {
preg_replace('/ \z/', '', $result); # Trim trailing space if we added one earlier.
}
return $result;
}
-
- function SmartDashes($text, $attr = NULL, $ctx = NULL) {
+ /**
+ * Replaces dashes with proper em and en dashes. Unused?
+ *
+ * @param $text The text to parse
+ * @param $attr The flag to what kind of processing we're doing.
+ *
+ * @return The processed text
+ */
+ function smartDashes($text, $attr = NULL) {
# Paramaters:
$text; # text to be parsed
$attr; # value of the smart_dashes="" attribute
- $ctx; # MT context object (unused)
if ($attr == NULL) $attr = $this->smartypants_attr;
# reference to the subroutine to use for dash education, default to EducateDashes:
$dash_sub_ref = 'EducateDashes';
if ($attr == 0) {
# do nothing;
return $text;
}
else if ($attr == 2) {
# use old smart dash shortcuts, "--" for en, "---" for em
$dash_sub_ref = 'EducateDashesOldSchool';
}
else if ($attr == 3) {
# inverse of 2, "--" for em, "---" for en
$dash_sub_ref = 'EducateDashesOldSchoolInverted';
}
$tokens;
$tokens = $this->TokenizeHTML($text);
$result = '';
$in_pre = 0; # Keep track of when we're inside <pre> or <code> tags
foreach ($tokens as $cur_token) {
if ($cur_token[0] == "tag") {
# Don't mess with quotes inside tags
$result .= $cur_token[1];
if (preg_match("@$this->sp_tags_to_skip@", $cur_token[1], $matches)) {
$in_pre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
}
} else {
$t = $cur_token[1];
if (! $in_pre) {
$t = $this->ProcessEscapes($t);
$t = $dash_sub_ref($t);
}
$result .= $t;
}
}
return $result;
}
-
- function SmartEllipses($text, $attr = NULL, $ctx = NULL) {
+ /**
+ * Replaces ... or . . . with proper … Unused?
+ *
+ * @param $text The text to parse
+ * @param $attr The flag to what kind of processing we're doing.
+ *
+ * @return The processed text
+ */
+ function smartEllipses($text, $attr = NULL) {
# Paramaters:
$text; # text to be parsed
$attr; # value of the smart_ellipses="" attribute
- $ctx; # MT context object (unused)
if ($attr == NULL) $attr = $this->smartypants_attr;
if ($attr == 0) {
# do nothing;
return $text;
}
$tokens;
$tokens = $this->TokenizeHTML($text);
$result = '';
$in_pre = 0; # Keep track of when we're inside <pre> or <code> tags
foreach ($tokens as $cur_token) {
if ($cur_token[0] == "tag") {
# Don't mess with quotes inside tags
$result .= $cur_token[1];
if (preg_match("@$this->sp_tags_to_skip@", $cur_token[1], $matches)) {
$in_pre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
}
} else {
$t = $cur_token[1];
if (! $in_pre) {
$t = $this->ProcessEscapes($t);
$t = $this->EducateEllipses($t);
}
$result .= $t;
}
}
return $result;
}
+ /**
+ * Process quotes into HTML entities
+ *
+ * Example input: "Isn't this fun?"
+ * Example output: “Isn’t this fun?”
+ *
+ * @param $_ String to process
+ *
+ * @return The string, with "educated" curly quote HTML entities.
+ */
+ function educateQuotes($_) {
- function EducateQuotes($_) {
- #
- # Parameter: String.
- #
- # Returns: The string, with "educated" curly quote HTML entities.
- #
- # Example input: "Isn't this fun?"
- # Example output: “Isn’t this fun?”
- #
# Make our own "punctuation" character class, because the POSIX-style
# [:PUNCT:] is only available in Perl 5.6 or later:
$punct_class = "[!\"#\\$\\%'()*+,-.\\/:;<=>?\\@\\[\\\\\]\\^_`{|}~]";
# Special case if the very first character is a quote
# followed by punctuation at a non-word-break. Close the quotes by brute force:
$_ = preg_replace(
array("/^'(?=$punct_class\\B)/", "/^\"(?=$punct_class\\B)/"),
array('’', '”'), $_);
# Special case for double sets of quotes, e.g.:
# <p>He said, "'Quoted' words in a larger quote."</p>
$_ = preg_replace(
array("/\"'(?=\w)/", "/'\"(?=\w)/"),
array('“‘', '‘“'), $_);
# Special case for decade abbreviations (the '80s):
$_ = preg_replace("/'(?=\\d{2}s)/", '’', $_);
$close_class = '[^\ \t\r\n\[\{\(\-]';
$dec_dashes = '&\#8211;|&\#8212;';
# Get most opening single quotes:
$_ = preg_replace("{
(
\\s | # a whitespace char, or
| # a non-breaking space entity, or
-- | # dashes, or
&[mn]dash; | # named dash entities
$dec_dashes | # or decimal entities
&\\#x201[34]; # or hex
)
' # the quote
(?=\\w) # followed by a word character
}x", '\1‘', $_);
# Single closing quotes:
$_ = preg_replace("{
($close_class)?
'
(?(1)| # If $1 captured, then do nothing;
(?=\\s | s\\b) # otherwise, positive lookahead for a whitespace
) # char or an 's' at a word ending position. This
# is a special case to handle something like:
# \"<i>Custer</i>'s Last Stand.\"
}xi", '\1’', $_);
# Any remaining single quotes should be opening ones:
$_ = str_replace("'", '‘', $_);
# Get most opening double quotes:
$_ = preg_replace("{
(
\\s | # a whitespace char, or
| # a non-breaking space entity, or
-- | # dashes, or
&[mn]dash; | # named dash entities
$dec_dashes | # or decimal entities
&\\#x201[34]; # or hex
)
\" # the quote
(?=\\w) # followed by a word character
}x", '\1“', $_);
# Double closing quotes:
$_ = preg_replace("{
($close_class)?
\"
(?(1)|(?=\\s)) # If $1 captured, then do nothing;
# if not, then make sure the next char is whitespace.
}x", '\1”', $_);
# Any remaining quotes should be opening ones.
$_ = str_replace('"', '“', $_);
return $_;
}
-
- function EducateBackticks($_) {
- #
- # Parameter: String.
- # Returns: The string, with ``backticks'' -style double quotes
- # translated into HTML curly quote entities.
- #
- # Example input: ``Isn't this fun?''
- # Example output: “Isn't this fun?”
- #
+ /**
+ * Process backticks-style doublequotes translated into proper HTML entities
+ * Example input: ``Isn't this fun?''
+ * Example output: “Isn't this fun?”
+ *
+ * @param $_ The string to convert backticks in
+ *
+ * @return The processed string
+ */
+ function educateBackticks($_) {
$_ = str_replace(array("``", "''",),
array('“', '”'), $_);
return $_;
}
-
+ /**
+ * Formats string with `backticks' -style single quotes
+ * translated into HTML curly quote entities.
+ * Example input: `Isn't this fun?'
+ * Example output: ‘Isn’t this fun?’
+ *
+ * @param $_ The string to process
+ *
+ * @return The processed string
+ */
function EducateSingleBackticks($_) {
- #
- # Parameter: String.
- # Returns: The string, with `backticks' -style single quotes
- # translated into HTML curly quote entities.
- #
- # Example input: `Isn't this fun?'
- # Example output: ‘Isn’t this fun?’
- #
-
$_ = str_replace(array("`", "'",),
array('‘', '’'), $_);
return $_;
}
-
+ /**
+ * Processes a string with each instance of "--" translated to
+ * an em-dash HTML entity.
+ *
+ * @param $_ The strong to process
+ *
+ * @return The processed string
+ *
+ */
function EducateDashes($_) {
- #
- # Parameter: String.
- #
- # Returns: The string, with each instance of "--" translated to
- # an em-dash HTML entity.
- #
-
$_ = str_replace('--', '—', $_);
return $_;
}
-
+ /**
+ * Processes a string with each instance of "--" translated to
+ * an en-dash HTML entity, and each "---" translated to
+ * an em-dash HTML entity.
+ *
+ * @param $_ The string to process
+ *
+ * @return The processed string
+ */
function EducateDashesOldSchool($_) {
- #
- # Parameter: String.
- #
- # Returns: The string, with each instance of "--" translated to
- # an en-dash HTML entity, and each "---" translated to
- # an em-dash HTML entity.
- #
-
- # em en
+ // em en
$_ = str_replace(array("---", "--",),
array('—', '–'), $_);
return $_;
}
-
+ /**
+ * Processes a string, with each instance of "--" translated to
+ * an em-dash HTML entity, and each "---" translated to
+ * an en-dash HTML entity. Two reasons why: First, unlike the
+ * en- and em-dash syntax supported by
+ * EducateDashesOldSchool(), it's compatible with existing
+ * entries written before SmartyPants 1.1, back when "--" was
+ * only used for em-dashes. Second, em-dashes are more
+ * common than en-dashes, and so it sort of makes sense that
+ * the shortcut should be shorter to type. (Thanks to Aaron
+ * Swartz for the idea.)
+ *
+ * @param $_ The string to process
+ *
+ * @return The processed string
+ */
function EducateDashesOldSchoolInverted($_) {
- #
- # Parameter: String.
- #
- # Returns: The string, with each instance of "--" translated to
- # an em-dash HTML entity, and each "---" translated to
- # an en-dash HTML entity. Two reasons why: First, unlike the
- # en- and em-dash syntax supported by
- # EducateDashesOldSchool(), it's compatible with existing
- # entries written before SmartyPants 1.1, back when "--" was
- # only used for em-dashes. Second, em-dashes are more
- # common than en-dashes, and so it sort of makes sense that
- # the shortcut should be shorter to type. (Thanks to Aaron
- # Swartz for the idea.)
- #
-
- # en em
+ // en em
$_ = str_replace(array("---", "--",),
array('–', '—'), $_);
return $_;
}
-
+ /**
+ * Processes a string with each instance of "..." translated to
+ * an ellipsis HTML entity. Also converts the case where
+ * there are spaces between the dots.
+ *
+ * Example input: Huh...?
+ * Example output: Huh…?
+ *
+ * @param $_ The string to process
+ *
+ * @return The processed string
+ */
function EducateEllipses($_) {
- #
- # Parameter: String.
- # Returns: The string, with each instance of "..." translated to
- # an ellipsis HTML entity. Also converts the case where
- # there are spaces between the dots.
- #
- # Example input: Huh...?
- # Example output: Huh…?
- #
-
$_ = str_replace(array("...", ". . .",), '…', $_);
return $_;
}
-
+ /**
+ * Processes a string, with each SmartyPants HTML entity translated to
+ * its ASCII counterpart.
+ *
+ * Example input: “Hello — world.”
+ * Example output: "Hello -- world."
+ *
+ * @param $_ The string to process
+ *
+ * @return The processed string
+ */
function StupefyEntities($_) {
- #
- # Parameter: String.
- # Returns: The string, with each SmartyPants HTML entity translated to
- # its ASCII counterpart.
- #
- # Example input: “Hello — world.”
- # Example output: "Hello -- world."
- #
-
- # en-dash em-dash
+ // en-dash em-dash
$_ = str_replace(array('–', '—'),
array('-', '--'), $_);
- # single quote open close
+ // single quote open close
$_ = str_replace(array('‘', '’'), "'", $_);
- # double quote open close
+ // double quote open close
$_ = str_replace(array('“', '”'), '"', $_);
- $_ = str_replace('…', '...', $_); # ellipsis
+ $_ = str_replace('…', '...', $_); // ellipsis
return $_;
}
-
+ /**
+ * Processes a string, with after processing the following backslash
+ * escape sequences. This is useful if you want to force a "dumb"
+ * quote or other character to appear.
+ *
+ * Escape Value
+ * ------ -----
+ * \\ \
+ * \" "
+ * \' '
+ * \. .
+ * \- -
+ * \` `
+ *
+ * @param $_ The string to process.
+ *
+ * @return The processed string
+ */
function ProcessEscapes($_) {
- #
- # Parameter: String.
- # Returns: The string, with after processing the following backslash
- # escape sequences. This is useful if you want to force a "dumb"
- # quote or other character to appear.
- #
- # Escape Value
- # ------ -----
- # \\ \
- # \" "
- # \' '
- # \. .
- # \- -
- # \` `
- #
$_ = str_replace(
array('\\\\', '\"', "\'", '\.', '\-', '\`'),
array('\', '"', ''', '.', '-', '`'), $_);
return $_;
}
-
+ /**
+ * Processes a string, and transforms it into an array of the tokens comprising the input
+ * string. Each token is either a tag (possibly with nested,
+ * tags contained therein, such as <a href="<MTFoo>">, or a
+ * run of text between tags. Each element of the array is a
+ * two-element array; the first is either 'tag' or 'text';
+ * the second is the actual value.
+ *
+ * Regular expression derived from the _tokenize() subroutine in
+ * Brad Choate's MTRegex plugin.
+ * <http://www.bradchoate.com/past/mtregex.php>
+ *
+ * @param $str String containing HTML markup.
+ *
+ * @return The tokenized array
+ */
function TokenizeHTML($str) {
- #
- # Parameter: String containing HTML markup.
- # Returns: An array of the tokens comprising the input
- # string. Each token is either a tag (possibly with nested,
- # tags contained therein, such as <a href="<MTFoo>">, or a
- # run of text between tags. Each element of the array is a
- # two-element array; the first is either 'tag' or 'text';
- # the second is the actual value.
- #
- #
- # Regular expression derived from the _tokenize() subroutine in
- # Brad Choate's MTRegex plugin.
- # <http://www.bradchoate.com/past/mtregex.php>
- #
$index = 0;
$tokens = array();
$match = '(?s:<!(?:--.*?--\s*)+>)|'. # comment
'(?s:<\?.*?\?>)|'. # processing instruction
# regular tags
'(?:<[/!$]?[-a-zA-Z0-9:]+\b(?>[^"\'>]+|"[^"]*"|\'[^\']*\')*>)';
$parts = preg_split("{($match)}", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($parts as $part) {
if (++$index % 2 && $part != '')
$tokens[] = array('text', $part);
else
$tokens[] = array('tag', $part);
}
return $tokens;
}
}
+
/*
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the php-typogrify nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
* Neither the name "SmartyPants" nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
* Neither the name "CakePHP TypogrifyHelper" nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=============
php-typogrify
=============
Announcement:
<http://www2.jeffcroft.com/sidenotes/2007/may/29/typogrify-easily-produce-web-typography-doesnt-suc/>
Example Page:
<http://static.mintchaos.com/projects/typogrify/>
Project Page:
<http://code.google.com/p/typogrify/>
PHP SmartyPants
<http://www.michelf.com/projects/php-smartypants/>
===============
PHP SmartyPants
===============
Smart punctuation for web sites
by John Gruber
<http://daringfireball.net>
PHP port by Michel Fortin
<http://www.michelf.com/>
Copyright (c) 2003-2004 John Gruber
Copyright (c) 2004-2005 Michel Fortin
Description
-----------
This is a PHP translation of the original SmartyPants quote educator written in
Perl by John Gruber.
SmartyPants is a web publishing utility that translates plain ASCII
punctuation characters into "smart" typographic punctuation HTML
entities. SmartyPants can perform the following transformations:
* Straight quotes (`"` and `'`) into "curly" quote HTML entities
* Backticks-style quotes (` ``like this'' `) into "curly" quote HTML
entities
* Dashes (`--` and `---`) into en- and em-dash entities
* Three consecutive dots (`...`) into an ellipsis entity
SmartyPants does not modify characters within `<pre>`, `<code>`, `<kbd>`,
`<script>`, or `<math>` tag blocks. Typically, these tags are used to
display text where smart quotes and other "smart punctuation" would not
be appropriate, such as source code or example markup.
### Backslash Escapes ###
If you need to use literal straight quotes (or plain hyphens and
periods), SmartyPants accepts the following backslash escape sequences
to force non-smart punctuation. It does so by transforming the escape
sequence into a decimal-encoded HTML entity:
Escape Value Character
------ ----- ---------
\\ \ \
\" " "
\' ' '
\. . .
\- - -
\` ` `
This is useful, for example, when you want to use straight quotes as
foot and inch marks: 6'2" tall; a 17" iMac.
-
-Bugs
-----
-
-To file bug reports or feature requests (other than topics listed in the
-Caveats section above) please send email to:
-
-<[email protected]>
-
-If the bug involves quotes being curled the wrong way, please send example
-text to illustrate.
-
-
### Algorithmic Shortcomings ###
One situation in which quotes will get curled the wrong way is when
apostrophes are used at the start of leading contractions. For example:
'Twas the night before Christmas.
In the case above, SmartyPants will turn the apostrophe into an opening
single-quote, when in fact it should be a closing one. I don't think
this problem can be solved in the general case -- every word processor
I've tried gets this wrong as well. In such cases, it's best to use the
proper HTML entity for closing single-quotes (`’`) by hand.
-Version History
----------------
-
-1.5.1e (9 Dec 2005)
-
-* Corrected a bug that prevented special characters from being
- escaped.
-
-
-1.5.1d (25 May 2005)
-
-* Corrected a small bug in `_TokenizeHTML` where a Doctype declaration
- was not seen as HTML (smart quotes where applied inside).
-
-
-1.5.1c (13 Dec 2004)
-
-* Changed a regular expression in `_TokenizeHTML` that could lead to
- a segmentation fault with PHP 4.3.8 on Linux.
-
-
-1.5.1b (6 Sep 2004)
-
-* Corrected a problem with quotes immediately following a dash
- with no space between: `Text--"quoted text"--text.`
-
-* PHP SmartyPants can now be used as a modifier by the Smarty
- template engine. Rename the file to "modifier.smartypants.php"
- and put it in your smarty plugins folder.
-
-* Replaced a lot of space characters by tabs, saving about 4 KB.
-
-
-1.5.1a (30 Jun 2004)
-
-* PHP Markdown and PHP Smartypants now share the same `_TokenizeHTML`
- function when loaded simultanously.
-
-* Changed the internals of `_TokenizeHTML` to lower the PHP version
- requirement to PHP 4.0.5.
-
-
-1.5.1 (6 Jun 2004)
-
-* Initial release of PHP SmartyPants, based on version 1.5.1 of the
- original SmartyPants written in Perl.
-
-
Author
------
John Gruber
<http://daringfireball.net/>
Ported to PHP by Michel Fortin
<http://www.michelf.com/>
Additional Credits
------------------
Portions of this plug-in are based on Brad Choate's nifty MTRegex plug-in.
Brad Choate also contributed a few bits of source code to this plug-in.
Brad Choate is a fine hacker indeed. (<http://bradchoate.com/>)
Jeremy Hedley (<http://antipixel.com/>) and Charles Wiltgen
(<http://playbacktime.com/>) deserve mention for exemplary beta testing.
*/
?>
\ No newline at end of file
|
davethegr8/cakephp-typogrify-helper
|
1369cfbf54f3db0eb1913ac02a03fc55e2b7d544
|
added readme info
|
diff --git a/README b/README
index e69de29..22d27f5 100644
--- a/README
+++ b/README
@@ -0,0 +1,18 @@
+TypogrifyHelper for CakePHP is a conversion of the typogrify module
+for Drupal. It is based off of php-typogrify and PHP SmartyPants.
+
+To use this Helper, just follow these steps:
+
+ To initalize the helper in whatever function you want it to be usable in
+
+ function view($id = NULL) {
+ $this->helpers[] = 'Typogrify';
+
+ /*
+ * Do some other data processing before passing control off to the view
+ */
+ }
+
+ To parse text and display the tyopgrified output
+
+ <?php echo $typogrify->parse($text) ?>
\ No newline at end of file
diff --git a/typogrify.php b/typogrify.php
index 33f092d..73b4e12 100644
--- a/typogrify.php
+++ b/typogrify.php
@@ -1,527 +1,526 @@
<?php
/*
===============================================================
CakePHP TypogrifyHelper, based on php-typogrify and PHP SmartyPants
================================================================
Prettifies your web typography by preventing ugly quotes and 'widows'
and providing CSS hooks to style some special cases.
License information follows at the end of this file.
==============================================================
CakePHP TypogrifyHelper Copyright (c) 2009, Dave Poole <http://www.zastica.com>
php-typogrify Copyright (c) 2007, Hamish Macpherson
-
php-typogriphy is a port of the original Python code by Christian Metts.
SmartyPants Copyright (c) 2003-2004 John Gruber <http://daringfireball.net>
PHP SmartyPants Copyright (c) 2004-2005 Michel Fortin <http://www.michelf.com/>
All rights reserved.
*/
class TypogrifyHelper extends AppHelper {
public $SmartyPantsPHPVersion;
public $SmartyPantsSyntaxVersion;
public $smartypants_attr;
public $sp_tags_to_skip;
function TypogrifyHelper() {
$this->SmartyPantsPHPVersion = '1.5.1e'; # Fru 9 Dec 2005
$this->SmartyPantsSyntaxVersion = '1.5.1'; # Fri 12 Mar 2004
# Configurable variables:
$this->smartypants_attr = "1"; # Change this to configure.
# 1 => "--" for em-dashes; no en-dash support
# 2 => "---" for em-dashes; "--" for en-dashes
# 3 => "--" for em-dashes; "---" for en-dashes
# See docs for more configuration options.
# Globals:
$this->sp_tags_to_skip = '<(/?)(?:pre|code|kbd|script|math)[\s>]';
}
/* Main Typogrify Function */
function parse($text, $do_guillemets = false) {
$text = $this->amp( $text );
$text = $this->widont( $text );
$text = $this->SmartyPants( $text );
$text = $this->caps( $text );
$text = $this->initial_quotes( $text, $do_guillemets );
$text = $this->dash( $text );
return $this->output($text);
}
/**
* amp
*
* Wraps ampersands in html with ``<span class="amp">`` so they can be
* styled with CSS. Ampersands are also normalized to ``&``. Requires
* ampersands to have whitespace or an `` `` on both sides.
*
* It won't mess up & that are already wrapped, in entities or URLs
*/
function amp( $text )
{
$amp_finder = "/(\s| )(&|&|&\#38;|&)(\s| )/";
return preg_replace($amp_finder, '\\1<span class="amp">&</span>\\3', $text);
}
/**
* widont
*
* Replaces the space between the last two words in a string with `` ``
* Works in these block tags ``(h1-h6, p, li)`` and also accounts for
* potential closing inline elements ``a, em, strong, span, b, i``
*
* Empty HTMLs shouldn't error
*/
function widont( $text )
{
// This regex is a beast, tread lightly
$widont_finder = "/([^\s])\s+(((<(a|span|i|b|em|strong|acronym|caps|sub|sup|abbr|big|small|code|cite|tt)[^>]*>)*\s*[^\s<>]+)(<\/(a|span|i|b|em|strong|acronym|caps|sub|sup|abbr|big|small|code|cite|tt)>)*[^\s<>]*\s*(<\/(p|h[1-6]|li)>|$))/i";
return preg_replace($widont_finder, '$1 $2', $text);
}
/**
* dash
*
* Puts a   before and after an &ndash or —
* Dashes may have whitespace or an `` `` on both sides
*/
function dash( $text )
{
$dash_finder = "/(\s| | )*(—|–|–|–|—|—)(\s| | )*/";
return preg_replace($dash_finder, ' \\2 ', $text);
}
/**
* caps
*
* Wraps multiple capital letters in ``<span class="caps">``
* so they can be styled with CSS.
*
* Uses the smartypants tokenizer to not screw with HTML or with tags it shouldn't.
*/
function caps( $text )
{
// Tokenize; see smartypants.php
$tokens = $this->TokenizeHTML($text);
$result = array();
$in_skipped_tag = false;
$cap_finder = "/(
(\b[A-Z\d]* # Group 2: Any amount of caps and digits
[A-Z]\d*[A-Z] # A cap string much at least include two caps (but they can have digits between them)
[A-Z\d]*\b) # Any amount of caps and digits
| (\b[A-Z]+\.\s? # OR: Group 3: Some caps, followed by a '.' and an optional space
(?:[A-Z]+\.\s?)+) # Followed by the same thing at least once more
(?:\s|\b|$))/x";
$tags_to_skip_regex = "/<(\/)?(?:pre|code|kbd|script|math)[^>]*>/i";
foreach ($tokens as $token)
{
if ( $token[0] == "tag" )
{
// Don't mess with tags.
$result[] = $token[1];
$close_match = preg_match($tags_to_skip_regex, $token[1]);
if ( $close_match )
{
$in_skipped_tag = true;
}
else
{
$in_skipped_tag = false;
}
}
else
{
if ( $in_skipped_tag )
{
$result[] = $token[1];
}
else
{
$result[] = preg_replace_callback($cap_finder, array('typogrifyhelper', '_cap_wrapper'), $token[1]);
}
}
}
return join("", $result);
}
/**
* This is necessary to keep dotted cap strings to pick up extra spaces
* used in preg_replace_callback later on
*/
function _cap_wrapper( $matchobj )
{
if ( !empty($matchobj[2]) )
{
return sprintf('<span class="caps">%s</span>', $matchobj[2]);
}
else
{
$mthree = $matchobj[3];
if ( ($mthree{strlen($mthree)-1}) == " " )
{
$caps = substr($mthree, 0, -1);
$tail = ' ';
}
else
{
$caps = $mthree;
$tail = '';
}
return sprintf('<span class="caps">%s</span>%s', $caps, $tail);
}
}
/**
* initial_quotes
*
* Wraps initial quotes in ``class="dquo"`` for double quotes or
* ``class="quo"`` for single quotes. Works in these block tags ``(h1-h6, p, li)``
* and also accounts for potential opening inline elements ``a, em, strong, span, b, i``
* Optionally choose to apply quote span tags to Gullemets as well.
*/
function initial_quotes( $text, $do_guillemets = false )
{
$quote_finder = "/((<(p|h[1-6]|li)[^>]*>|^) # start with an opening p, h1-6, li or the start of the string
\s* # optional white space!
(<(a|em|span|strong|i|b)[^>]*>\s*)*) # optional opening inline tags, with more optional white space for each.
((\"|“|&\#8220;)|('|‘|&\#8216;)) # Find me a quote! (only need to find the left quotes and the primes)
# double quotes are in group 7, singles in group 8
/ix";
if ($do_guillemets)
{
$quote_finder = "/((<(p|h[1-6]|li)[^>]*>|^) # start with an opening p, h1-6, li or the start of the string
\s* # optional white space!
(<(a|em|span|strong|i|b)[^>]*>\s*)*) # optional opening inline tags, with more optional white space for each.
((\"|“|&\#8220;|\xAE|&\#171;|«)|('|‘|&\#8216;)) # Find me a quote! (only need to find the left quotes and the primes) - also look for guillemets (>> and << characters))
# double quotes are in group 7, singles in group 8
/ix";
}
return preg_replace_callback($quote_finder, array('typogrifyhelper', '_quote_wrapper'), $text);
}
function _quote_wrapper( $matchobj )
{
if ( !empty($matchobj[7]) )
{
$classname = "dquo";
$quote = $matchobj[7];
}
else
{
$classname = "quo";
$quote = $matchobj[8];
}
return sprintf('%s<span class="%s">%s</span>', $matchobj[1], $classname, $quote);
}
//SmartyPants fuctions
function SmartyPants($text, $attr = NULL, $ctx = NULL) {
# Paramaters:
$text; # text to be parsed
$attr; # value of the smart_quotes="" attribute
$ctx; # MT context object (unused)
if ($attr == NULL) $attr = $this->smartypants_attr;
# Options to specify which transformations to make:
$do_stupefy = FALSE;
$convert_quot = 0; # should we translate " entities into normal quotes?
# Parse attributes:
# 0 : do nothing
# 1 : set all
# 2 : set all, using old school en- and em- dash shortcuts
# 3 : set all, using inverted old school en and em- dash shortcuts
#
# q : quotes
# b : backtick quotes (``double'' only)
# B : backtick quotes (``double'' and `single')
# d : dashes
# D : old school dashes
# i : inverted old school dashes
# e : ellipses
# w : convert " entities to " for Dreamweaver users
if ($attr == "0") {
# Do nothing.
return $text;
}
else if ($attr == "1") {
# Do everything, turn all options on.
$do_quotes = 1;
$do_backticks = 1;
$do_dashes = 1;
$do_ellipses = 1;
}
else if ($attr == "2") {
# Do everything, turn all options on, use old school dash shorthand.
$do_quotes = 1;
$do_backticks = 1;
$do_dashes = 2;
$do_ellipses = 1;
}
else if ($attr == "3") {
# Do everything, turn all options on, use inverted old school dash shorthand.
$do_quotes = 1;
$do_backticks = 1;
$do_dashes = 3;
$do_ellipses = 1;
}
else if ($attr == "-1") {
# Special "stupefy" mode.
$do_stupefy = 1;
}
else {
$chars = preg_split('//', $attr);
foreach ($chars as $c){
if ($c == "q") { $do_quotes = 1; }
else if ($c == "b") { $do_backticks = 1; }
else if ($c == "B") { $do_backticks = 2; }
else if ($c == "d") { $do_dashes = 1; }
else if ($c == "D") { $do_dashes = 2; }
else if ($c == "i") { $do_dashes = 3; }
else if ($c == "e") { $do_ellipses = 1; }
else if ($c == "w") { $convert_quot = 1; }
else {
# Unknown attribute option, ignore.
}
}
}
$tokens = $this->TokenizeHTML($text);
$result = '';
$in_pre = 0; # Keep track of when we're inside <pre> or <code> tags.
$prev_token_last_char = ""; # This is a cheat, used to get some context
# for one-character tokens that consist of
# just a quote char. What we do is remember
# the last character of the previous text
# token, to use as context to curl single-
# character quote tokens correctly.
foreach ($tokens as $cur_token) {
if ($cur_token[0] == "tag") {
# Don't mess with quotes inside tags.
$result .= $cur_token[1];
if (preg_match("@$this->sp_tags_to_skip@", $cur_token[1], $matches)) {
$in_pre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
}
} else {
$t = $cur_token[1];
$last_char = substr($t, -1); # Remember last char of this token before processing.
if (! $in_pre) {
$t = $this->ProcessEscapes($t);
if ($convert_quot) {
$t = preg_replace('/"/', '"', $t);
}
if ($do_dashes) {
if ($do_dashes == 1) $t = $this->EducateDashes($t);
if ($do_dashes == 2) $t = $this->EducateDashesOldSchool($t);
if ($do_dashes == 3) $t = $this->EducateDashesOldSchoolInverted($t);
}
if ($do_ellipses) $t = $this->EducateEllipses($t);
# Note: backticks need to be processed before quotes.
if ($do_backticks) {
$t = $this->EducateBackticks($t);
if ($do_backticks == 2) $t = $this->EducateSingleBackticks($t);
}
if ($do_quotes) {
if ($t == "'") {
# Special case: single-character ' token
if (preg_match('/\S/', $prev_token_last_char)) {
$t = "’";
}
else {
$t = "‘";
}
}
else if ($t == '"') {
# Special case: single-character " token
if (preg_match('/\S/', $prev_token_last_char)) {
$t = "”";
}
else {
$t = "“";
}
}
else {
# Normal case:
$t = $this->EducateQuotes($t);
}
}
if ($do_stupefy) $t = $this->StupefyEntities($t);
}
$prev_token_last_char = $last_char;
$result .= $t;
}
}
return $result;
}
function SmartQuotes($text, $attr = NULL, $ctx = NULL) {
# Paramaters:
$text; # text to be parsed
$attr; # value of the smart_quotes="" attribute
$ctx; # MT context object (unused)
if ($attr == NULL) $attr = $this->smartypants_attr;
$do_backticks; # should we educate ``backticks'' -style quotes?
if ($attr == 0) {
# do nothing;
return $text;
}
else if ($attr == 2) {
# smarten ``backticks'' -style quotes
$do_backticks = 1;
}
else {
$do_backticks = 0;
}
# Special case to handle quotes at the very end of $text when preceded by
# an HTML tag. Add a space to give the quote education algorithm a bit of
# context, so that it can guess correctly that it's a closing quote:
$add_extra_space = 0;
if (preg_match("/>['\"]\\z/", $text)) {
$add_extra_space = 1; # Remember, so we can trim the extra space later.
$text .= " ";
}
$tokens = $this->TokenizeHTML($text);
$result = '';
$in_pre = 0; # Keep track of when we're inside <pre> or <code> tags
$prev_token_last_char = ""; # This is a cheat, used to get some context
# for one-character tokens that consist of
# just a quote char. What we do is remember
# the last character of the previous text
# token, to use as context to curl single-
# character quote tokens correctly.
foreach ($tokens as $cur_token) {
if ($cur_token[0] == "tag") {
# Don't mess with quotes inside tags
$result .= $cur_token[1];
if (preg_match("@$this->sp_tags_to_skip@", $cur_token[1], $matches)) {
$in_pre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
}
} else {
$t = $cur_token[1];
$last_char = substr($t, -1); # Remember last char of this token before processing.
if (! $in_pre) {
$t = $this->ProcessEscapes($t);
if ($do_backticks) {
$t = $this->EducateBackticks($t);
}
if ($t == "'") {
# Special case: single-character ' token
if (preg_match('/\S/', $prev_token_last_char)) {
$t = "’";
}
else {
$t = "‘";
}
}
else if ($t == '"') {
# Special case: single-character " token
if (preg_match('/\S/', $prev_token_last_char)) {
$t = "”";
}
else {
$t = "“";
}
}
else {
# Normal case:
$t = $this->EducateQuotes($t);
}
}
$prev_token_last_char = $last_char;
$result .= $t;
}
}
if ($add_extra_space) {
preg_replace('/ \z/', '', $result); # Trim trailing space if we added one earlier.
}
return $result;
}
function SmartDashes($text, $attr = NULL, $ctx = NULL) {
# Paramaters:
$text; # text to be parsed
$attr; # value of the smart_dashes="" attribute
$ctx; # MT context object (unused)
if ($attr == NULL) $attr = $this->smartypants_attr;
# reference to the subroutine to use for dash education, default to EducateDashes:
$dash_sub_ref = 'EducateDashes';
if ($attr == 0) {
# do nothing;
return $text;
}
else if ($attr == 2) {
# use old smart dash shortcuts, "--" for en, "---" for em
$dash_sub_ref = 'EducateDashesOldSchool';
}
else if ($attr == 3) {
# inverse of 2, "--" for em, "---" for en
$dash_sub_ref = 'EducateDashesOldSchoolInverted';
}
$tokens;
$tokens = $this->TokenizeHTML($text);
$result = '';
$in_pre = 0; # Keep track of when we're inside <pre> or <code> tags
foreach ($tokens as $cur_token) {
if ($cur_token[0] == "tag") {
# Don't mess with quotes inside tags
$result .= $cur_token[1];
if (preg_match("@$this->sp_tags_to_skip@", $cur_token[1], $matches)) {
$in_pre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
}
} else {
$t = $cur_token[1];
if (! $in_pre) {
$t = $this->ProcessEscapes($t);
$t = $dash_sub_ref($t);
}
$result .= $t;
}
}
return $result;
|
gregkh/samsung-backlight
|
871976e0427bbe8c8385b0e73c17fbef379a85d8
|
Added README saying this repo is now old and not to be used.
|
diff --git a/README b/README
new file mode 100644
index 0000000..db03767
--- /dev/null
+++ b/README
@@ -0,0 +1,10 @@
+Please use the version of this driver that is in the Linux kernel main
+tree in the drivers/platform/x86/ directory. It is the latest version,
+and includes all of the needed fixes and supports a wider range of
+devices than this one does.
+
+This repo is just the old history of how the driver was developed
+originally, and is not to be run by anyone on any machines anymore.
+
+If anyone has questions about this, please contact me:
+ Greg Kroah-Hartman <[email protected]>
|
gregkh/samsung-backlight
|
5b4e3ed757677a81cf9e83e542755d9204bd26bc
|
Fix driver to work with newer kernel versions
|
diff --git a/samsung-backlight.c b/samsung-backlight.c
index 342ad96..5854b60 100644
--- a/samsung-backlight.c
+++ b/samsung-backlight.c
@@ -1,179 +1,182 @@
/*
* Samsung N130 and NC10 Laptop Backlight driver
*
* Copyright (C) 2009 Greg Kroah-Hartman ([email protected])
* Copyright (C) 2009 Novell Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/backlight.h>
#include <linux/fb.h>
#include <linux/dmi.h>
#define MAX_BRIGHT 0x07
#define OFFSET 0xf4
/*
* HAL/gnome-display-manager really wants us to only set 8 different levels for
* the brightness control. And since 256 different levels seems a bit
* overkill, that's fine. So let's map the 256 values to 8 different ones:
*
* userspace 0 1 2 3 4 5 6 7
* hardware 31 63 95 127 159 195 223 255
*
* or hardware = ((userspace + 1) * 32)-1
*
* Note, we keep value 0 at a positive value, otherwise the screen goes
* blank because HAL likes to set the backlight to 0 at startup when there is
* no power plugged in.
*/
static int offset = OFFSET;
module_param(offset, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(offset, "The offset into the PCI device for the brightness control");
static struct pci_dev *pci_device;
static struct backlight_device *backlight_device;
static u8 read_brightness(void)
{
u8 kernel_brightness;
u8 user_brightness = 0;
pci_read_config_byte(pci_device, offset, &kernel_brightness);
user_brightness = ((kernel_brightness + 1) / 32) - 1;
return user_brightness;
}
static void set_brightness(u8 user_brightness)
{
u16 kernel_brightness = 0;
kernel_brightness = ((user_brightness + 1) * 32) - 1;
pci_write_config_byte(pci_device, offset, (u8)kernel_brightness);
}
static int get_brightness(struct backlight_device *bd)
{
return bd->props.brightness;
}
static int update_status(struct backlight_device *bd)
{
set_brightness(bd->props.brightness);
return 0;
}
static struct backlight_ops backlight_ops = {
.get_brightness = get_brightness,
.update_status = update_status,
};
static int __init dmi_check_cb(const struct dmi_system_id *id)
{
printk(KERN_INFO KBUILD_MODNAME ": found laptop model '%s'\n",
id->ident);
return 0;
}
static struct dmi_system_id __initdata samsung_dmi_table[] = {
{
.ident = "N120",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "N120"),
DMI_MATCH(DMI_BOARD_NAME, "N120"),
},
.callback = dmi_check_cb,
},
{
.ident = "N130",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "N130"),
DMI_MATCH(DMI_BOARD_NAME, "N130"),
},
.callback = dmi_check_cb,
},
{
.ident = "NC10",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "NC10"),
DMI_MATCH(DMI_BOARD_NAME, "NC10"),
},
.callback = dmi_check_cb,
},
{
.ident = "NP-Q45",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "SQ45S70S"),
DMI_MATCH(DMI_BOARD_NAME, "SQ45S70S"),
},
.callback = dmi_check_cb,
},
{ },
};
static int __init samsung_init(void)
{
+ struct backlight_properties props;
+ memset(&props, 0, sizeof(struct backlight_properties));
+
if (!dmi_check_system(samsung_dmi_table))
return -ENODEV;
/*
* The Samsung N120, N130, and NC10 use pci device id 0x27ae, while the
* NP-Q45 uses 0x2a02. Odds are we might need to add more to the
* list over time...
*/
pci_device = pci_get_device(PCI_VENDOR_ID_INTEL, 0x27ae, NULL);
if (!pci_device) {
pci_device = pci_get_device(PCI_VENDOR_ID_INTEL, 0x2a02, NULL);
if (!pci_device)
return -ENODEV;
}
/* create a backlight device to talk to this one */
backlight_device = backlight_device_register("samsung",
&pci_device->dev,
- NULL, &backlight_ops);
+ NULL, &backlight_ops, &props);
if (IS_ERR(backlight_device)) {
pci_dev_put(pci_device);
return PTR_ERR(backlight_device);
}
backlight_device->props.max_brightness = MAX_BRIGHT;
backlight_device->props.brightness = read_brightness();
backlight_device->props.power = FB_BLANK_UNBLANK;
backlight_update_status(backlight_device);
return 0;
}
static void __exit samsung_exit(void)
{
backlight_device_unregister(backlight_device);
/* we are done with the PCI device, put it back */
pci_dev_put(pci_device);
}
module_init(samsung_init);
module_exit(samsung_exit);
MODULE_AUTHOR("Greg Kroah-Hartman <[email protected]>");
MODULE_DESCRIPTION("Samsung Backlight driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN120:*:rnN120:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN130:*:rnN130:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnNC10:*:rnNC10:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnSQ45S70S:*:rnSQ45S70S:*");
|
gregkh/samsung-backlight
|
cb0feb7ba6094ceb05505fee659e898709ae078e
|
make value 0 actually show something.
|
diff --git a/samsung-backlight.c b/samsung-backlight.c
index 411b324..342ad96 100644
--- a/samsung-backlight.c
+++ b/samsung-backlight.c
@@ -1,178 +1,179 @@
/*
* Samsung N130 and NC10 Laptop Backlight driver
*
* Copyright (C) 2009 Greg Kroah-Hartman ([email protected])
* Copyright (C) 2009 Novell Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/backlight.h>
#include <linux/fb.h>
#include <linux/dmi.h>
#define MAX_BRIGHT 0x07
#define OFFSET 0xf4
/*
* HAL/gnome-display-manager really wants us to only set 8 different levels for
* the brightness control. And since 256 different levels seems a bit
* overkill, that's fine. So let's map the 256 values to 8 different ones:
*
- * userspace 0 1 2 3 4 5 6 7
- * hardware 0 36 72 108 144 180 216 252
+ * userspace 0 1 2 3 4 5 6 7
+ * hardware 31 63 95 127 159 195 223 255
*
- * or hardware = (userspace * 36) - 1 iff userspace != 0
+ * or hardware = ((userspace + 1) * 32)-1
+ *
+ * Note, we keep value 0 at a positive value, otherwise the screen goes
+ * blank because HAL likes to set the backlight to 0 at startup when there is
+ * no power plugged in.
*/
static int offset = OFFSET;
module_param(offset, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(offset, "The offset into the PCI device for the brightness control");
static struct pci_dev *pci_device;
static struct backlight_device *backlight_device;
static u8 read_brightness(void)
{
u8 kernel_brightness;
u8 user_brightness = 0;
pci_read_config_byte(pci_device, offset, &kernel_brightness);
- if (kernel_brightness != 0)
- user_brightness = kernel_brightness / 36;
-
+ user_brightness = ((kernel_brightness + 1) / 32) - 1;
return user_brightness;
}
static void set_brightness(u8 user_brightness)
{
u16 kernel_brightness = 0;
- if (user_brightness != 0)
- kernel_brightness = (user_brightness * 36) - 1;
+ kernel_brightness = ((user_brightness + 1) * 32) - 1;
pci_write_config_byte(pci_device, offset, (u8)kernel_brightness);
}
static int get_brightness(struct backlight_device *bd)
{
return bd->props.brightness;
}
static int update_status(struct backlight_device *bd)
{
set_brightness(bd->props.brightness);
return 0;
}
static struct backlight_ops backlight_ops = {
.get_brightness = get_brightness,
.update_status = update_status,
};
static int __init dmi_check_cb(const struct dmi_system_id *id)
{
printk(KERN_INFO KBUILD_MODNAME ": found laptop model '%s'\n",
id->ident);
return 0;
}
static struct dmi_system_id __initdata samsung_dmi_table[] = {
{
.ident = "N120",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "N120"),
DMI_MATCH(DMI_BOARD_NAME, "N120"),
},
.callback = dmi_check_cb,
},
{
.ident = "N130",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "N130"),
DMI_MATCH(DMI_BOARD_NAME, "N130"),
},
.callback = dmi_check_cb,
},
{
.ident = "NC10",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "NC10"),
DMI_MATCH(DMI_BOARD_NAME, "NC10"),
},
.callback = dmi_check_cb,
},
{
.ident = "NP-Q45",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "SQ45S70S"),
DMI_MATCH(DMI_BOARD_NAME, "SQ45S70S"),
},
.callback = dmi_check_cb,
},
{ },
};
static int __init samsung_init(void)
{
if (!dmi_check_system(samsung_dmi_table))
return -ENODEV;
/*
* The Samsung N120, N130, and NC10 use pci device id 0x27ae, while the
* NP-Q45 uses 0x2a02. Odds are we might need to add more to the
* list over time...
*/
pci_device = pci_get_device(PCI_VENDOR_ID_INTEL, 0x27ae, NULL);
if (!pci_device) {
pci_device = pci_get_device(PCI_VENDOR_ID_INTEL, 0x2a02, NULL);
if (!pci_device)
return -ENODEV;
}
/* create a backlight device to talk to this one */
backlight_device = backlight_device_register("samsung",
&pci_device->dev,
NULL, &backlight_ops);
if (IS_ERR(backlight_device)) {
pci_dev_put(pci_device);
return PTR_ERR(backlight_device);
}
backlight_device->props.max_brightness = MAX_BRIGHT;
backlight_device->props.brightness = read_brightness();
backlight_device->props.power = FB_BLANK_UNBLANK;
backlight_update_status(backlight_device);
return 0;
}
static void __exit samsung_exit(void)
{
backlight_device_unregister(backlight_device);
/* we are done with the PCI device, put it back */
pci_dev_put(pci_device);
}
module_init(samsung_init);
module_exit(samsung_exit);
MODULE_AUTHOR("Greg Kroah-Hartman <[email protected]>");
MODULE_DESCRIPTION("Samsung Backlight driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN120:*:rnN120:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN130:*:rnN130:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnNC10:*:rnNC10:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnSQ45S70S:*:rnSQ45S70S:*");
|
gregkh/samsung-backlight
|
22e16dd8950234a7ae87d45fe9cedc28cc3ea41f
|
me do math guud
|
diff --git a/samsung-backlight.c b/samsung-backlight.c
index 466be0e..411b324 100644
--- a/samsung-backlight.c
+++ b/samsung-backlight.c
@@ -1,178 +1,178 @@
/*
* Samsung N130 and NC10 Laptop Backlight driver
*
* Copyright (C) 2009 Greg Kroah-Hartman ([email protected])
* Copyright (C) 2009 Novell Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/backlight.h>
#include <linux/fb.h>
#include <linux/dmi.h>
#define MAX_BRIGHT 0x07
#define OFFSET 0xf4
/*
* HAL/gnome-display-manager really wants us to only set 8 different levels for
* the brightness control. And since 256 different levels seems a bit
* overkill, that's fine. So let's map the 256 values to 8 different ones:
*
* userspace 0 1 2 3 4 5 6 7
- * hardware 0 31 63 95 127 159 191 255
+ * hardware 0 36 72 108 144 180 216 252
*
- * or hardware = (userspace * 32) - 1 iff userspace != 0
+ * or hardware = (userspace * 36) - 1 iff userspace != 0
*/
static int offset = OFFSET;
module_param(offset, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(offset, "The offset into the PCI device for the brightness control");
static struct pci_dev *pci_device;
static struct backlight_device *backlight_device;
static u8 read_brightness(void)
{
u8 kernel_brightness;
u8 user_brightness = 0;
pci_read_config_byte(pci_device, offset, &kernel_brightness);
if (kernel_brightness != 0)
- user_brightness = kernel_brightness / 32;
+ user_brightness = kernel_brightness / 36;
return user_brightness;
}
static void set_brightness(u8 user_brightness)
{
u16 kernel_brightness = 0;
if (user_brightness != 0)
- kernel_brightness = (user_brightness * 32) - 1;
+ kernel_brightness = (user_brightness * 36) - 1;
pci_write_config_byte(pci_device, offset, (u8)kernel_brightness);
}
static int get_brightness(struct backlight_device *bd)
{
return bd->props.brightness;
}
static int update_status(struct backlight_device *bd)
{
set_brightness(bd->props.brightness);
return 0;
}
static struct backlight_ops backlight_ops = {
.get_brightness = get_brightness,
.update_status = update_status,
};
static int __init dmi_check_cb(const struct dmi_system_id *id)
{
printk(KERN_INFO KBUILD_MODNAME ": found laptop model '%s'\n",
id->ident);
return 0;
}
static struct dmi_system_id __initdata samsung_dmi_table[] = {
{
.ident = "N120",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "N120"),
DMI_MATCH(DMI_BOARD_NAME, "N120"),
},
.callback = dmi_check_cb,
},
{
.ident = "N130",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "N130"),
DMI_MATCH(DMI_BOARD_NAME, "N130"),
},
.callback = dmi_check_cb,
},
{
.ident = "NC10",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "NC10"),
DMI_MATCH(DMI_BOARD_NAME, "NC10"),
},
.callback = dmi_check_cb,
},
{
.ident = "NP-Q45",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "SQ45S70S"),
DMI_MATCH(DMI_BOARD_NAME, "SQ45S70S"),
},
.callback = dmi_check_cb,
},
{ },
};
static int __init samsung_init(void)
{
if (!dmi_check_system(samsung_dmi_table))
return -ENODEV;
/*
* The Samsung N120, N130, and NC10 use pci device id 0x27ae, while the
* NP-Q45 uses 0x2a02. Odds are we might need to add more to the
* list over time...
*/
pci_device = pci_get_device(PCI_VENDOR_ID_INTEL, 0x27ae, NULL);
if (!pci_device) {
pci_device = pci_get_device(PCI_VENDOR_ID_INTEL, 0x2a02, NULL);
if (!pci_device)
return -ENODEV;
}
/* create a backlight device to talk to this one */
backlight_device = backlight_device_register("samsung",
&pci_device->dev,
NULL, &backlight_ops);
if (IS_ERR(backlight_device)) {
pci_dev_put(pci_device);
return PTR_ERR(backlight_device);
}
backlight_device->props.max_brightness = MAX_BRIGHT;
backlight_device->props.brightness = read_brightness();
backlight_device->props.power = FB_BLANK_UNBLANK;
backlight_update_status(backlight_device);
return 0;
}
static void __exit samsung_exit(void)
{
backlight_device_unregister(backlight_device);
/* we are done with the PCI device, put it back */
pci_dev_put(pci_device);
}
module_init(samsung_init);
module_exit(samsung_exit);
MODULE_AUTHOR("Greg Kroah-Hartman <[email protected]>");
MODULE_DESCRIPTION("Samsung Backlight driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN120:*:rnN120:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN130:*:rnN130:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnNC10:*:rnNC10:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnSQ45S70S:*:rnSQ45S70S:*");
|
gregkh/samsung-backlight
|
886c2ee63d52a18ef076214e280d76d88fa5f597
|
first cut at moving the values to be between 0 and 7
|
diff --git a/samsung-backlight.c b/samsung-backlight.c
index 3581cd0..466be0e 100644
--- a/samsung-backlight.c
+++ b/samsung-backlight.c
@@ -1,158 +1,178 @@
/*
* Samsung N130 and NC10 Laptop Backlight driver
*
* Copyright (C) 2009 Greg Kroah-Hartman ([email protected])
* Copyright (C) 2009 Novell Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/backlight.h>
#include <linux/fb.h>
#include <linux/dmi.h>
-#define MAX_BRIGHT 0xff
+#define MAX_BRIGHT 0x07
#define OFFSET 0xf4
+/*
+ * HAL/gnome-display-manager really wants us to only set 8 different levels for
+ * the brightness control. And since 256 different levels seems a bit
+ * overkill, that's fine. So let's map the 256 values to 8 different ones:
+ *
+ * userspace 0 1 2 3 4 5 6 7
+ * hardware 0 31 63 95 127 159 191 255
+ *
+ * or hardware = (userspace * 32) - 1 iff userspace != 0
+ */
+
+
static int offset = OFFSET;
module_param(offset, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(offset, "The offset into the PCI device for the brightness control");
static struct pci_dev *pci_device;
static struct backlight_device *backlight_device;
static u8 read_brightness(void)
{
- u8 brightness;
+ u8 kernel_brightness;
+ u8 user_brightness = 0;
- pci_read_config_byte(pci_device, offset, &brightness);
- return brightness;
+ pci_read_config_byte(pci_device, offset, &kernel_brightness);
+ if (kernel_brightness != 0)
+ user_brightness = kernel_brightness / 32;
+
+ return user_brightness;
}
-static void set_brightness(u8 brightness)
+static void set_brightness(u8 user_brightness)
{
- pci_write_config_byte(pci_device, offset, brightness);
+ u16 kernel_brightness = 0;
+
+ if (user_brightness != 0)
+ kernel_brightness = (user_brightness * 32) - 1;
+ pci_write_config_byte(pci_device, offset, (u8)kernel_brightness);
}
static int get_brightness(struct backlight_device *bd)
{
return bd->props.brightness;
}
static int update_status(struct backlight_device *bd)
{
set_brightness(bd->props.brightness);
return 0;
}
static struct backlight_ops backlight_ops = {
.get_brightness = get_brightness,
.update_status = update_status,
};
static int __init dmi_check_cb(const struct dmi_system_id *id)
{
printk(KERN_INFO KBUILD_MODNAME ": found laptop model '%s'\n",
id->ident);
return 0;
}
static struct dmi_system_id __initdata samsung_dmi_table[] = {
{
.ident = "N120",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "N120"),
DMI_MATCH(DMI_BOARD_NAME, "N120"),
},
.callback = dmi_check_cb,
},
{
.ident = "N130",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "N130"),
DMI_MATCH(DMI_BOARD_NAME, "N130"),
},
.callback = dmi_check_cb,
},
{
.ident = "NC10",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "NC10"),
DMI_MATCH(DMI_BOARD_NAME, "NC10"),
},
.callback = dmi_check_cb,
},
{
.ident = "NP-Q45",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "SQ45S70S"),
DMI_MATCH(DMI_BOARD_NAME, "SQ45S70S"),
},
.callback = dmi_check_cb,
},
{ },
};
static int __init samsung_init(void)
{
if (!dmi_check_system(samsung_dmi_table))
return -ENODEV;
/*
* The Samsung N120, N130, and NC10 use pci device id 0x27ae, while the
* NP-Q45 uses 0x2a02. Odds are we might need to add more to the
* list over time...
*/
pci_device = pci_get_device(PCI_VENDOR_ID_INTEL, 0x27ae, NULL);
if (!pci_device) {
pci_device = pci_get_device(PCI_VENDOR_ID_INTEL, 0x2a02, NULL);
if (!pci_device)
return -ENODEV;
}
/* create a backlight device to talk to this one */
backlight_device = backlight_device_register("samsung",
&pci_device->dev,
NULL, &backlight_ops);
if (IS_ERR(backlight_device)) {
pci_dev_put(pci_device);
return PTR_ERR(backlight_device);
}
backlight_device->props.max_brightness = MAX_BRIGHT;
backlight_device->props.brightness = read_brightness();
backlight_device->props.power = FB_BLANK_UNBLANK;
backlight_update_status(backlight_device);
return 0;
}
static void __exit samsung_exit(void)
{
backlight_device_unregister(backlight_device);
/* we are done with the PCI device, put it back */
pci_dev_put(pci_device);
}
module_init(samsung_init);
module_exit(samsung_exit);
MODULE_AUTHOR("Greg Kroah-Hartman <[email protected]>");
MODULE_DESCRIPTION("Samsung Backlight driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN120:*:rnN120:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN130:*:rnN130:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnNC10:*:rnNC10:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnSQ45S70S:*:rnSQ45S70S:*");
|
gregkh/samsung-backlight
|
66973ab6a58161afcc00a2fba10ab6d905e87b98
|
added N120 support, and lots of cleanups from Dmitry
|
diff --git a/samsung-backlight.c b/samsung-backlight.c
index accc20e..3581cd0 100644
--- a/samsung-backlight.c
+++ b/samsung-backlight.c
@@ -1,168 +1,158 @@
/*
* Samsung N130 and NC10 Laptop Backlight driver
*
* Copyright (C) 2009 Greg Kroah-Hartman ([email protected])
* Copyright (C) 2009 Novell Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/backlight.h>
#include <linux/fb.h>
#include <linux/dmi.h>
#define MAX_BRIGHT 0xff
#define OFFSET 0xf4
+static int offset = OFFSET;
+module_param(offset, int, S_IRUGO | S_IWUSR);
+MODULE_PARM_DESC(offset, "The offset into the PCI device for the brightness control");
+
static struct pci_dev *pci_device;
static struct backlight_device *backlight_device;
-static int offset = OFFSET;
-static u8 current_brightness;
-static void read_brightness(void)
+static u8 read_brightness(void)
{
- if (!pci_device)
- return;
- pci_read_config_byte(pci_device, offset, ¤t_brightness);
+ u8 brightness;
+
+ pci_read_config_byte(pci_device, offset, &brightness);
+ return brightness;
}
-static void set_brightness(void)
+static void set_brightness(u8 brightness)
{
- if (!pci_device)
- return;
- pci_write_config_byte(pci_device, offset, current_brightness);
+ pci_write_config_byte(pci_device, offset, brightness);
}
static int get_brightness(struct backlight_device *bd)
{
return bd->props.brightness;
}
static int update_status(struct backlight_device *bd)
{
- if (!pci_device)
- return -ENODEV;
-
- current_brightness = bd->props.brightness;
- set_brightness();
+ set_brightness(bd->props.brightness);
return 0;
}
static struct backlight_ops backlight_ops = {
.get_brightness = get_brightness,
.update_status = update_status,
};
-static int find_video_card(void)
-{
- struct pci_dev *dev = NULL;
-
- while ((dev = pci_get_device(0x8086, 0x27ae, dev)) != NULL) {
- /*
- * Found one, so let's save it off and break
- * Note that the reference is still raised on
- * the PCI device here.
- */
- pci_device = dev;
- break;
- }
-
- if (!pci_device)
- return -ENODEV;
-
- /* create a backlight device to talk to this one */
- backlight_device = backlight_device_register("samsung",
- &pci_device->dev,
- NULL, &backlight_ops);
- if (IS_ERR(backlight_device))
- return PTR_ERR(backlight_device);
- read_brightness();
- backlight_device->props.max_brightness = MAX_BRIGHT;
- backlight_device->props.brightness = current_brightness;
- backlight_device->props.power = FB_BLANK_UNBLANK;
- backlight_update_status(backlight_device);
- return 0;
-}
-
-static void remove_video_card(void)
-{
- if (!pci_device)
- return;
-
- backlight_device_unregister(backlight_device);
- backlight_device = NULL;
-
- /* we are done with the PCI device, put it back */
- pci_dev_put(pci_device);
- pci_device = NULL;
-}
-
-static int dmi_check_cb(const struct dmi_system_id *id)
+static int __init dmi_check_cb(const struct dmi_system_id *id)
{
printk(KERN_INFO KBUILD_MODNAME ": found laptop model '%s'\n",
id->ident);
return 0;
}
static struct dmi_system_id __initdata samsung_dmi_table[] = {
+ {
+ .ident = "N120",
+ .matches = {
+ DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
+ DMI_MATCH(DMI_PRODUCT_NAME, "N120"),
+ DMI_MATCH(DMI_BOARD_NAME, "N120"),
+ },
+ .callback = dmi_check_cb,
+ },
{
.ident = "N130",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "N130"),
DMI_MATCH(DMI_BOARD_NAME, "N130"),
},
.callback = dmi_check_cb,
},
{
.ident = "NC10",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "NC10"),
DMI_MATCH(DMI_BOARD_NAME, "NC10"),
},
.callback = dmi_check_cb,
},
{
.ident = "NP-Q45",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "SQ45S70S"),
DMI_MATCH(DMI_BOARD_NAME, "SQ45S70S"),
},
.callback = dmi_check_cb,
},
{ },
};
static int __init samsung_init(void)
{
if (!dmi_check_system(samsung_dmi_table))
return -ENODEV;
- return find_video_card();
+ /*
+ * The Samsung N120, N130, and NC10 use pci device id 0x27ae, while the
+ * NP-Q45 uses 0x2a02. Odds are we might need to add more to the
+ * list over time...
+ */
+ pci_device = pci_get_device(PCI_VENDOR_ID_INTEL, 0x27ae, NULL);
+ if (!pci_device) {
+ pci_device = pci_get_device(PCI_VENDOR_ID_INTEL, 0x2a02, NULL);
+ if (!pci_device)
+ return -ENODEV;
+ }
+
+ /* create a backlight device to talk to this one */
+ backlight_device = backlight_device_register("samsung",
+ &pci_device->dev,
+ NULL, &backlight_ops);
+ if (IS_ERR(backlight_device)) {
+ pci_dev_put(pci_device);
+ return PTR_ERR(backlight_device);
+ }
+
+ backlight_device->props.max_brightness = MAX_BRIGHT;
+ backlight_device->props.brightness = read_brightness();
+ backlight_device->props.power = FB_BLANK_UNBLANK;
+ backlight_update_status(backlight_device);
+
+ return 0;
}
static void __exit samsung_exit(void)
{
- remove_video_card();
+ backlight_device_unregister(backlight_device);
+
+ /* we are done with the PCI device, put it back */
+ pci_dev_put(pci_device);
}
module_init(samsung_init);
module_exit(samsung_exit);
MODULE_AUTHOR("Greg Kroah-Hartman <[email protected]>");
MODULE_DESCRIPTION("Samsung Backlight driver");
MODULE_LICENSE("GPL");
-module_param(offset, int, S_IRUGO | S_IWUSR);
-MODULE_PARM_DESC(offset, "The offset into the PCI device for the brightness control");
+MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN120:*:rnN120:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN130:*:rnN130:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnNC10:*:rnNC10:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnSQ45S70S:*:rnSQ45S70S:*");
|
gregkh/samsung-backlight
|
6ecfda3f1d5d0c12b588382bca0b81dd7a7bf8a0
|
Support for the Samsung NP-Q45 from Jérémie Huchet added
|
diff --git a/samsung-backlight.c b/samsung-backlight.c
index 2e38e63..accc20e 100644
--- a/samsung-backlight.c
+++ b/samsung-backlight.c
@@ -1,158 +1,168 @@
/*
* Samsung N130 and NC10 Laptop Backlight driver
*
* Copyright (C) 2009 Greg Kroah-Hartman ([email protected])
* Copyright (C) 2009 Novell Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/backlight.h>
#include <linux/fb.h>
#include <linux/dmi.h>
#define MAX_BRIGHT 0xff
#define OFFSET 0xf4
static struct pci_dev *pci_device;
static struct backlight_device *backlight_device;
static int offset = OFFSET;
static u8 current_brightness;
static void read_brightness(void)
{
if (!pci_device)
return;
pci_read_config_byte(pci_device, offset, ¤t_brightness);
}
static void set_brightness(void)
{
if (!pci_device)
return;
pci_write_config_byte(pci_device, offset, current_brightness);
}
static int get_brightness(struct backlight_device *bd)
{
return bd->props.brightness;
}
static int update_status(struct backlight_device *bd)
{
if (!pci_device)
return -ENODEV;
current_brightness = bd->props.brightness;
set_brightness();
return 0;
}
static struct backlight_ops backlight_ops = {
.get_brightness = get_brightness,
.update_status = update_status,
};
static int find_video_card(void)
{
struct pci_dev *dev = NULL;
while ((dev = pci_get_device(0x8086, 0x27ae, dev)) != NULL) {
/*
* Found one, so let's save it off and break
* Note that the reference is still raised on
* the PCI device here.
*/
pci_device = dev;
break;
}
if (!pci_device)
return -ENODEV;
/* create a backlight device to talk to this one */
backlight_device = backlight_device_register("samsung",
&pci_device->dev,
NULL, &backlight_ops);
if (IS_ERR(backlight_device))
return PTR_ERR(backlight_device);
read_brightness();
backlight_device->props.max_brightness = MAX_BRIGHT;
backlight_device->props.brightness = current_brightness;
backlight_device->props.power = FB_BLANK_UNBLANK;
backlight_update_status(backlight_device);
return 0;
}
static void remove_video_card(void)
{
if (!pci_device)
return;
backlight_device_unregister(backlight_device);
backlight_device = NULL;
/* we are done with the PCI device, put it back */
pci_dev_put(pci_device);
pci_device = NULL;
}
static int dmi_check_cb(const struct dmi_system_id *id)
{
printk(KERN_INFO KBUILD_MODNAME ": found laptop model '%s'\n",
id->ident);
return 0;
}
static struct dmi_system_id __initdata samsung_dmi_table[] = {
{
.ident = "N130",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "N130"),
DMI_MATCH(DMI_BOARD_NAME, "N130"),
},
.callback = dmi_check_cb,
},
{
.ident = "NC10",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "NC10"),
DMI_MATCH(DMI_BOARD_NAME, "NC10"),
},
.callback = dmi_check_cb,
},
+ {
+ .ident = "NP-Q45",
+ .matches = {
+ DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
+ DMI_MATCH(DMI_PRODUCT_NAME, "SQ45S70S"),
+ DMI_MATCH(DMI_BOARD_NAME, "SQ45S70S"),
+ },
+ .callback = dmi_check_cb,
+ },
{ },
};
static int __init samsung_init(void)
{
if (!dmi_check_system(samsung_dmi_table))
return -ENODEV;
return find_video_card();
}
static void __exit samsung_exit(void)
{
remove_video_card();
}
module_init(samsung_init);
module_exit(samsung_exit);
MODULE_AUTHOR("Greg Kroah-Hartman <[email protected]>");
MODULE_DESCRIPTION("Samsung Backlight driver");
MODULE_LICENSE("GPL");
module_param(offset, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(offset, "The offset into the PCI device for the brightness control");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN130:*:rnN130:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnNC10:*:rnNC10:*");
+MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnSQ45S70S:*:rnSQ45S70S:*");
|
gregkh/samsung-backlight
|
0b769c01b2cf35227e9f0a2ad50d9ba34f693cd3
|
fix up the "if we don't find the device, what do we do?" logic a bit
|
diff --git a/samsung-backlight.c b/samsung-backlight.c
index 63395c2..2e38e63 100644
--- a/samsung-backlight.c
+++ b/samsung-backlight.c
@@ -1,156 +1,158 @@
/*
- * Samsung N130 Laptop Backlight driver
+ * Samsung N130 and NC10 Laptop Backlight driver
*
* Copyright (C) 2009 Greg Kroah-Hartman ([email protected])
* Copyright (C) 2009 Novell Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/backlight.h>
#include <linux/fb.h>
#include <linux/dmi.h>
#define MAX_BRIGHT 0xff
#define OFFSET 0xf4
static struct pci_dev *pci_device;
static struct backlight_device *backlight_device;
static int offset = OFFSET;
static u8 current_brightness;
static void read_brightness(void)
{
if (!pci_device)
return;
pci_read_config_byte(pci_device, offset, ¤t_brightness);
}
static void set_brightness(void)
{
if (!pci_device)
return;
pci_write_config_byte(pci_device, offset, current_brightness);
}
static int get_brightness(struct backlight_device *bd)
{
return bd->props.brightness;
}
static int update_status(struct backlight_device *bd)
{
if (!pci_device)
return -ENODEV;
- if (!backlight_device)
- return -ENODEV;
current_brightness = bd->props.brightness;
set_brightness();
return 0;
}
static struct backlight_ops backlight_ops = {
.get_brightness = get_brightness,
.update_status = update_status,
};
static int find_video_card(void)
{
struct pci_dev *dev = NULL;
while ((dev = pci_get_device(0x8086, 0x27ae, dev)) != NULL) {
- /* Found one, so let's save it off */
- if (!pci_device)
- pci_device = pci_dev_get(dev);
+ /*
+ * Found one, so let's save it off and break
+ * Note that the reference is still raised on
+ * the PCI device here.
+ */
+ pci_device = dev;
+ break;
}
if (!pci_device)
- return 0;
+ return -ENODEV;
/* create a backlight device to talk to this one */
backlight_device = backlight_device_register("samsung",
&pci_device->dev,
NULL, &backlight_ops);
if (IS_ERR(backlight_device))
return PTR_ERR(backlight_device);
read_brightness();
backlight_device->props.max_brightness = MAX_BRIGHT;
backlight_device->props.brightness = current_brightness;
backlight_device->props.power = FB_BLANK_UNBLANK;
backlight_update_status(backlight_device);
return 0;
}
static void remove_video_card(void)
{
if (!pci_device)
return;
backlight_device_unregister(backlight_device);
backlight_device = NULL;
/* we are done with the PCI device, put it back */
pci_dev_put(pci_device);
pci_device = NULL;
}
static int dmi_check_cb(const struct dmi_system_id *id)
{
printk(KERN_INFO KBUILD_MODNAME ": found laptop model '%s'\n",
id->ident);
return 0;
}
static struct dmi_system_id __initdata samsung_dmi_table[] = {
{
.ident = "N130",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "N130"),
DMI_MATCH(DMI_BOARD_NAME, "N130"),
},
.callback = dmi_check_cb,
},
{
.ident = "NC10",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "NC10"),
DMI_MATCH(DMI_BOARD_NAME, "NC10"),
},
.callback = dmi_check_cb,
},
{ },
};
static int __init samsung_init(void)
{
if (!dmi_check_system(samsung_dmi_table))
return -ENODEV;
return find_video_card();
}
static void __exit samsung_exit(void)
{
remove_video_card();
}
module_init(samsung_init);
module_exit(samsung_exit);
MODULE_AUTHOR("Greg Kroah-Hartman <[email protected]>");
-MODULE_DESCRIPTION("Samsung N130 Backlight driver");
+MODULE_DESCRIPTION("Samsung Backlight driver");
MODULE_LICENSE("GPL");
module_param(offset, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(offset, "The offset into the PCI device for the brightness control");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN130:*:rnN130:*");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnNC10:*:rnNC10:*");
|
gregkh/samsung-backlight
|
9045774edddaf373f5d3359911bc01692a0ca96a
|
Added support for Samsung NC10 laptop
|
diff --git a/samsung-backlight.c b/samsung-backlight.c
index a8d501e..63395c2 100644
--- a/samsung-backlight.c
+++ b/samsung-backlight.c
@@ -1,146 +1,156 @@
/*
* Samsung N130 Laptop Backlight driver
*
* Copyright (C) 2009 Greg Kroah-Hartman ([email protected])
* Copyright (C) 2009 Novell Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/backlight.h>
#include <linux/fb.h>
#include <linux/dmi.h>
#define MAX_BRIGHT 0xff
#define OFFSET 0xf4
static struct pci_dev *pci_device;
static struct backlight_device *backlight_device;
static int offset = OFFSET;
static u8 current_brightness;
static void read_brightness(void)
{
if (!pci_device)
return;
pci_read_config_byte(pci_device, offset, ¤t_brightness);
}
static void set_brightness(void)
{
if (!pci_device)
return;
pci_write_config_byte(pci_device, offset, current_brightness);
}
static int get_brightness(struct backlight_device *bd)
{
return bd->props.brightness;
}
static int update_status(struct backlight_device *bd)
{
if (!pci_device)
return -ENODEV;
if (!backlight_device)
return -ENODEV;
current_brightness = bd->props.brightness;
set_brightness();
return 0;
}
static struct backlight_ops backlight_ops = {
.get_brightness = get_brightness,
.update_status = update_status,
};
static int find_video_card(void)
{
struct pci_dev *dev = NULL;
while ((dev = pci_get_device(0x8086, 0x27ae, dev)) != NULL) {
/* Found one, so let's save it off */
if (!pci_device)
pci_device = pci_dev_get(dev);
}
if (!pci_device)
return 0;
/* create a backlight device to talk to this one */
backlight_device = backlight_device_register("samsung",
&pci_device->dev,
NULL, &backlight_ops);
if (IS_ERR(backlight_device))
return PTR_ERR(backlight_device);
read_brightness();
backlight_device->props.max_brightness = MAX_BRIGHT;
backlight_device->props.brightness = current_brightness;
backlight_device->props.power = FB_BLANK_UNBLANK;
backlight_update_status(backlight_device);
return 0;
}
static void remove_video_card(void)
{
if (!pci_device)
return;
backlight_device_unregister(backlight_device);
backlight_device = NULL;
/* we are done with the PCI device, put it back */
pci_dev_put(pci_device);
pci_device = NULL;
}
static int dmi_check_cb(const struct dmi_system_id *id)
{
printk(KERN_INFO KBUILD_MODNAME ": found laptop model '%s'\n",
id->ident);
return 0;
}
static struct dmi_system_id __initdata samsung_dmi_table[] = {
{
.ident = "N130",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "N130"),
DMI_MATCH(DMI_BOARD_NAME, "N130"),
},
.callback = dmi_check_cb,
},
+ {
+ .ident = "NC10",
+ .matches = {
+ DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
+ DMI_MATCH(DMI_PRODUCT_NAME, "NC10"),
+ DMI_MATCH(DMI_BOARD_NAME, "NC10"),
+ },
+ .callback = dmi_check_cb,
+ },
{ },
};
static int __init samsung_init(void)
{
if (!dmi_check_system(samsung_dmi_table))
return -ENODEV;
return find_video_card();
}
static void __exit samsung_exit(void)
{
remove_video_card();
}
module_init(samsung_init);
module_exit(samsung_exit);
MODULE_AUTHOR("Greg Kroah-Hartman <[email protected]>");
MODULE_DESCRIPTION("Samsung N130 Backlight driver");
MODULE_LICENSE("GPL");
module_param(offset, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(offset, "The offset into the PCI device for the brightness control");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN130:*:rnN130:*");
+MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnNC10:*:rnNC10:*");
|
gregkh/samsung-backlight
|
ada1a638e12cca47e6e6f27e511934c7a13a3552
|
remove pci driver api, it's not needed to load the module automatically
|
diff --git a/samsung-backlight.c b/samsung-backlight.c
index 5ed4235..a8d501e 100644
--- a/samsung-backlight.c
+++ b/samsung-backlight.c
@@ -1,177 +1,146 @@
/*
* Samsung N130 Laptop Backlight driver
*
* Copyright (C) 2009 Greg Kroah-Hartman ([email protected])
* Copyright (C) 2009 Novell Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/backlight.h>
#include <linux/fb.h>
#include <linux/dmi.h>
#define MAX_BRIGHT 0xff
#define OFFSET 0xf4
static struct pci_dev *pci_device;
static struct backlight_device *backlight_device;
static int offset = OFFSET;
static u8 current_brightness;
-static struct pci_device_id samsung_ids[] = {
- { PCI_DEVICE(0x8086, 0x27ae) },
- { },
-};
-MODULE_DEVICE_TABLE(pci, samsung_ids);
-
-static int probe(struct pci_dev *pci_dev, const struct pci_device_id *id)
-{
- return -ENODEV;
-}
-
-static void remove(struct pci_dev *pci_dev)
-{
-}
-
-static struct pci_driver samsung_driver = {
- .name = "samsung-backlight",
- .id_table = samsung_ids,
- .probe = probe,
- .remove = remove,
-};
-
static void read_brightness(void)
{
if (!pci_device)
return;
pci_read_config_byte(pci_device, offset, ¤t_brightness);
}
static void set_brightness(void)
{
if (!pci_device)
return;
pci_write_config_byte(pci_device, offset, current_brightness);
}
-
static int get_brightness(struct backlight_device *bd)
{
return bd->props.brightness;
}
static int update_status(struct backlight_device *bd)
{
if (!pci_device)
return -ENODEV;
if (!backlight_device)
return -ENODEV;
current_brightness = bd->props.brightness;
set_brightness();
return 0;
}
static struct backlight_ops backlight_ops = {
.get_brightness = get_brightness,
.update_status = update_status,
};
-
static int find_video_card(void)
{
struct pci_dev *dev = NULL;
while ((dev = pci_get_device(0x8086, 0x27ae, dev)) != NULL) {
/* Found one, so let's save it off */
if (!pci_device)
pci_device = pci_dev_get(dev);
}
if (!pci_device)
return 0;
/* create a backlight device to talk to this one */
backlight_device = backlight_device_register("samsung",
&pci_device->dev,
NULL, &backlight_ops);
if (IS_ERR(backlight_device))
return PTR_ERR(backlight_device);
read_brightness();
backlight_device->props.max_brightness = MAX_BRIGHT;
backlight_device->props.brightness = current_brightness;
backlight_device->props.power = FB_BLANK_UNBLANK;
backlight_update_status(backlight_device);
return 0;
}
static void remove_video_card(void)
{
if (!pci_device)
return;
backlight_device_unregister(backlight_device);
backlight_device = NULL;
/* we are done with the PCI device, put it back */
pci_dev_put(pci_device);
pci_device = NULL;
}
static int dmi_check_cb(const struct dmi_system_id *id)
{
printk(KERN_INFO KBUILD_MODNAME ": found laptop model '%s'\n",
id->ident);
return 0;
}
static struct dmi_system_id __initdata samsung_dmi_table[] = {
{
.ident = "N130",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "N130"),
DMI_MATCH(DMI_BOARD_NAME, "N130"),
},
.callback = dmi_check_cb,
},
{ },
};
static int __init samsung_init(void)
{
- int retval;
-
if (!dmi_check_system(samsung_dmi_table))
return -ENODEV;
- retval = pci_register_driver(&samsung_driver);
- if (retval)
- return retval;
-
return find_video_card();
}
static void __exit samsung_exit(void)
{
- pci_unregister_driver(&samsung_driver);
remove_video_card();
}
module_init(samsung_init);
module_exit(samsung_exit);
MODULE_AUTHOR("Greg Kroah-Hartman <[email protected]>");
MODULE_DESCRIPTION("Samsung N130 Backlight driver");
MODULE_LICENSE("GPL");
module_param(offset, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(offset, "The offset into the PCI device for the brightness control");
MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN130:*:rnN130:*");
|
gregkh/samsung-backlight
|
9253b12802ed170545965efcbb9d7efd6de02f84
|
add dmi support to the driver
|
diff --git a/samsung-backlight.c b/samsung-backlight.c
index 4465f0b..5ed4235 100644
--- a/samsung-backlight.c
+++ b/samsung-backlight.c
@@ -1,151 +1,177 @@
/*
* Samsung N130 Laptop Backlight driver
*
* Copyright (C) 2009 Greg Kroah-Hartman ([email protected])
* Copyright (C) 2009 Novell Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/backlight.h>
#include <linux/fb.h>
+#include <linux/dmi.h>
#define MAX_BRIGHT 0xff
#define OFFSET 0xf4
static struct pci_dev *pci_device;
static struct backlight_device *backlight_device;
static int offset = OFFSET;
static u8 current_brightness;
static struct pci_device_id samsung_ids[] = {
{ PCI_DEVICE(0x8086, 0x27ae) },
{ },
};
MODULE_DEVICE_TABLE(pci, samsung_ids);
static int probe(struct pci_dev *pci_dev, const struct pci_device_id *id)
{
return -ENODEV;
}
static void remove(struct pci_dev *pci_dev)
{
}
static struct pci_driver samsung_driver = {
.name = "samsung-backlight",
.id_table = samsung_ids,
.probe = probe,
.remove = remove,
};
static void read_brightness(void)
{
if (!pci_device)
return;
pci_read_config_byte(pci_device, offset, ¤t_brightness);
}
static void set_brightness(void)
{
if (!pci_device)
return;
pci_write_config_byte(pci_device, offset, current_brightness);
}
static int get_brightness(struct backlight_device *bd)
{
return bd->props.brightness;
}
static int update_status(struct backlight_device *bd)
{
if (!pci_device)
return -ENODEV;
if (!backlight_device)
return -ENODEV;
current_brightness = bd->props.brightness;
set_brightness();
return 0;
}
static struct backlight_ops backlight_ops = {
.get_brightness = get_brightness,
.update_status = update_status,
};
static int find_video_card(void)
{
struct pci_dev *dev = NULL;
while ((dev = pci_get_device(0x8086, 0x27ae, dev)) != NULL) {
/* Found one, so let's save it off */
if (!pci_device)
pci_device = pci_dev_get(dev);
}
if (!pci_device)
return 0;
/* create a backlight device to talk to this one */
backlight_device = backlight_device_register("samsung",
&pci_device->dev,
NULL, &backlight_ops);
if (IS_ERR(backlight_device))
return PTR_ERR(backlight_device);
read_brightness();
backlight_device->props.max_brightness = MAX_BRIGHT;
backlight_device->props.brightness = current_brightness;
backlight_device->props.power = FB_BLANK_UNBLANK;
backlight_update_status(backlight_device);
return 0;
}
static void remove_video_card(void)
{
if (!pci_device)
return;
backlight_device_unregister(backlight_device);
backlight_device = NULL;
/* we are done with the PCI device, put it back */
pci_dev_put(pci_device);
pci_device = NULL;
}
+static int dmi_check_cb(const struct dmi_system_id *id)
+{
+ printk(KERN_INFO KBUILD_MODNAME ": found laptop model '%s'\n",
+ id->ident);
+ return 0;
+}
+
+static struct dmi_system_id __initdata samsung_dmi_table[] = {
+ {
+ .ident = "N130",
+ .matches = {
+ DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
+ DMI_MATCH(DMI_PRODUCT_NAME, "N130"),
+ DMI_MATCH(DMI_BOARD_NAME, "N130"),
+ },
+ .callback = dmi_check_cb,
+ },
+ { },
+};
+
static int __init samsung_init(void)
{
int retval;
+
+ if (!dmi_check_system(samsung_dmi_table))
+ return -ENODEV;
+
retval = pci_register_driver(&samsung_driver);
if (retval)
return retval;
return find_video_card();
}
static void __exit samsung_exit(void)
{
pci_unregister_driver(&samsung_driver);
remove_video_card();
}
module_init(samsung_init);
module_exit(samsung_exit);
MODULE_AUTHOR("Greg Kroah-Hartman <[email protected]>");
MODULE_DESCRIPTION("Samsung N130 Backlight driver");
MODULE_LICENSE("GPL");
module_param(offset, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(offset, "The offset into the PCI device for the brightness control");
+MODULE_ALIAS("dmi:*:svnSAMSUNGELECTRONICSCO.,LTD.:pnN130:*:rnN130:*");
|
gregkh/samsung-backlight
|
488d2f88e85857065aa22d7334320e69e4d8513c
|
add backlight class support
|
diff --git a/samsung-backlight.c b/samsung-backlight.c
index bfc9373..4465f0b 100644
--- a/samsung-backlight.c
+++ b/samsung-backlight.c
@@ -1,76 +1,151 @@
/*
* Samsung N130 Laptop Backlight driver
*
* Copyright (C) 2009 Greg Kroah-Hartman ([email protected])
* Copyright (C) 2009 Novell Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
+#include <linux/backlight.h>
+#include <linux/fb.h>
-static struct pci_dev *device;
+#define MAX_BRIGHT 0xff
+#define OFFSET 0xf4
+
+static struct pci_dev *pci_device;
+static struct backlight_device *backlight_device;
+static int offset = OFFSET;
+static u8 current_brightness;
static struct pci_device_id samsung_ids[] = {
{ PCI_DEVICE(0x8086, 0x27ae) },
{ },
};
MODULE_DEVICE_TABLE(pci, samsung_ids);
static int probe(struct pci_dev *pci_dev, const struct pci_device_id *id)
{
return -ENODEV;
}
static void remove(struct pci_dev *pci_dev)
{
}
static struct pci_driver samsung_driver = {
.name = "samsung-backlight",
.id_table = samsung_ids,
.probe = probe,
.remove = remove,
};
+static void read_brightness(void)
+{
+ if (!pci_device)
+ return;
+ pci_read_config_byte(pci_device, offset, ¤t_brightness);
+}
+
+static void set_brightness(void)
+{
+ if (!pci_device)
+ return;
+ pci_write_config_byte(pci_device, offset, current_brightness);
+}
+
+
+static int get_brightness(struct backlight_device *bd)
+{
+ return bd->props.brightness;
+}
+
+static int update_status(struct backlight_device *bd)
+{
+ if (!pci_device)
+ return -ENODEV;
+ if (!backlight_device)
+ return -ENODEV;
+
+ current_brightness = bd->props.brightness;
+ set_brightness();
+ return 0;
+}
+
+static struct backlight_ops backlight_ops = {
+ .get_brightness = get_brightness,
+ .update_status = update_status,
+};
+
static int find_video_card(void)
{
+ struct pci_dev *dev = NULL;
+
+ while ((dev = pci_get_device(0x8086, 0x27ae, dev)) != NULL) {
+ /* Found one, so let's save it off */
+ if (!pci_device)
+ pci_device = pci_dev_get(dev);
+ }
+ if (!pci_device)
+ return 0;
+
+ /* create a backlight device to talk to this one */
+ backlight_device = backlight_device_register("samsung",
+ &pci_device->dev,
+ NULL, &backlight_ops);
+ if (IS_ERR(backlight_device))
+ return PTR_ERR(backlight_device);
+ read_brightness();
+ backlight_device->props.max_brightness = MAX_BRIGHT;
+ backlight_device->props.brightness = current_brightness;
+ backlight_device->props.power = FB_BLANK_UNBLANK;
+ backlight_update_status(backlight_device);
return 0;
}
static void remove_video_card(void)
{
- if (!device)
+ if (!pci_device)
return;
+
+ backlight_device_unregister(backlight_device);
+ backlight_device = NULL;
+
+ /* we are done with the PCI device, put it back */
+ pci_dev_put(pci_device);
+ pci_device = NULL;
}
static int __init samsung_init(void)
{
int retval;
retval = pci_register_driver(&samsung_driver);
if (retval)
return retval;
return find_video_card();
}
static void __exit samsung_exit(void)
{
pci_unregister_driver(&samsung_driver);
remove_video_card();
}
module_init(samsung_init);
module_exit(samsung_exit);
MODULE_AUTHOR("Greg Kroah-Hartman <[email protected]>");
MODULE_DESCRIPTION("Samsung N130 Backlight driver");
MODULE_LICENSE("GPL");
+module_param(offset, int, S_IRUGO | S_IWUSR);
+MODULE_PARM_DESC(offset, "The offset into the PCI device for the brightness control");
|
gregkh/samsung-backlight
|
12845e79f486aeb261d01e0749cbfcdc94726f4e
|
initial pci structure for driver
|
diff --git a/samsung-backlight.c b/samsung-backlight.c
index 21c5209..bfc9373 100644
--- a/samsung-backlight.c
+++ b/samsung-backlight.c
@@ -1,20 +1,76 @@
+/*
+ * Samsung N130 Laptop Backlight driver
+ *
+ * Copyright (C) 2009 Greg Kroah-Hartman ([email protected])
+ * Copyright (C) 2009 Novell Inc.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 as published by
+ * the Free Software Foundation.
+ *
+ */
+
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
+#include <linux/pci.h>
+
+static struct pci_dev *device;
+
+static struct pci_device_id samsung_ids[] = {
+ { PCI_DEVICE(0x8086, 0x27ae) },
+ { },
+};
+MODULE_DEVICE_TABLE(pci, samsung_ids);
+
+static int probe(struct pci_dev *pci_dev, const struct pci_device_id *id)
+{
+ return -ENODEV;
+}
-static int __init gotemp_init(void)
+static void remove(struct pci_dev *pci_dev)
{
- printk(KERN_INFO "Hello from the kernel!\n");
+}
+
+static struct pci_driver samsung_driver = {
+ .name = "samsung-backlight",
+ .id_table = samsung_ids,
+ .probe = probe,
+ .remove = remove,
+};
+
+
+static int find_video_card(void)
+{
+
return 0;
}
-static void __exit gotemp_exit(void)
+static void remove_video_card(void)
+{
+ if (!device)
+ return;
+}
+
+static int __init samsung_init(void)
+{
+ int retval;
+ retval = pci_register_driver(&samsung_driver);
+ if (retval)
+ return retval;
+
+ return find_video_card();
+}
+
+static void __exit samsung_exit(void)
{
+ pci_unregister_driver(&samsung_driver);
+ remove_video_card();
}
-module_init(gotemp_init);
-module_exit(gotemp_exit);
+module_init(samsung_init);
+module_exit(samsung_exit);
-MODULE_AUTHOR("My name here");
-MODULE_DESCRIPTION("Simple driver");
+MODULE_AUTHOR("Greg Kroah-Hartman <[email protected]>");
+MODULE_DESCRIPTION("Samsung N130 Backlight driver");
MODULE_LICENSE("GPL");
|
shykes/mqtools
|
e6c4a9d5b598a2105d597eb84a5e41c48a105540
|
mqcat is send-only
|
diff --git a/mqcat.py b/mqcat.py
index d6961b3..90f2924 100644
--- a/mqcat.py
+++ b/mqcat.py
@@ -1,59 +1,42 @@
#!/usr/bin/env python
import sys
+import logging
import argparse
from carrot.connection import BrokerConnection
from carrot.messaging import Publisher, Consumer
parser = argparse.ArgumentParser(description="Read a text stream and send it to an AMQP broker")
-subcommands = parser.add_subparsers(dest="command")
-parser_consume = subcommands.add_parser("consume", help="consume amqp messages and write them to stdout")
-parser_consume.add_argument("hostname", help="Hostname of the AMQP broker")
-parser_consume.add_argument("queue", help="Queue to use on the AMQP broker")
-parser_consume.add_argument("--exchange", help="Create a fanout exchange and bind it to the queue", default=None)
-parser_consume.add_argument("-u", "--user", help="User for the AMQP broker", default=None)
-parser_consume.add_argument("-p", "--password", help="Password for the AMQP broker", default=None)
-parser_consume.add_argument("-v", "--vhost", help="Virtual host to use on the AMQP broker", default="/")
-parser_consume.add_argument("--ack", help="Acknowledge messages, removing them from the queue", action="store_true")
-
-parser_send = subcommands.add_parser("send", help="Read lines from stdin, send them to an amqp broker")
-parser_send.add_argument("hostname", help="Hostname of the AMQP broker")
-parser_send.add_argument("exchange", help="Exchange to use on the AMQP broker")
-parser_send.add_argument("--key", help="Routing key to use on the AMQP broker")
-parser_send.add_argument("-v", "--vhost", help="Virtual host to use on the AMQP broker", default="/")
-parser_send.add_argument("-u", "--user", help="User for the AMQP broker", default=None)
-parser_send.add_argument("-p", "--password", help="Password for the AMQP broker", default=None)
+parser.add_argument("hostname", help="Hostname of the AMQP broker")
+parser.add_argument("exchange", help="Exchange to use on the AMQP broker")
+parser.add_argument("--key", help="Routing key to use on the AMQP broker")
+parser.add_argument("-v", "--vhost", help="Virtual host to use on the AMQP broker", default="/")
+parser.add_argument("-u", "--user", help="User for the AMQP broker", default="guest")
+parser.add_argument("-p", "--password", help="Password for the AMQP broker", default="guest")
def main():
+ logging.basicConfig(level=logging.DEBUG)
args = parser.parse_args()
conn = BrokerConnection(
hostname=args.hostname,
virtual_host=args.vhost,
userid=args.user,
password=args.password,
)
- if args.command == "consume":
- consumer = Consumer(
- connection = conn,
- exchange_type = "fanout" if args.exchange else None,
- exchange = args.exchange,
- queue = args.queue
- )
- def display_message(data, msg):
- print str(data)
- if args.ack:
- msg.ack()
- consumer.register_callback(display_message)
- consumer.wait()
- elif args.command == "send":
- publisher = Publisher(
- auto_declare = False,
- connection = conn,
- exchange = args.exchange,
- routing_key = args.key
- )
- for line in sys.stdin.readlines():
- publisher.send(line.strip())
- publisher.close()
+ publisher = Publisher(
+ auto_declare = False,
+ connection = conn,
+ exchange = args.exchange,
+ routing_key = args.key
+ )
+ logging.info("Declaring exchange: %s" % args.exchange)
+ publisher.backend.exchange_declare(exchange=args.exchange, type="topic", durable=False, auto_delete=False)
+ while True:
+ line = sys.stdin.readline()
+ if not line:
+ break
+ logging.debug("Sending message '%s'" % line.strip())
+ publisher.send(line.strip())
+ publisher.close()
|
shykes/mqtools
|
ba8029dc8cd07278eefccab1f5e105bb4e6a67b0
|
mqsniff: non-destructively dump trafic on an exchange
|
diff --git a/bin/mqsniff b/bin/mqsniff
new file mode 100644
index 0000000..ade7a1b
--- /dev/null
+++ b/bin/mqsniff
@@ -0,0 +1,6 @@
+#!/usr/bin/env python
+
+from mqcat.mqsniff import main
+
+if __name__ == "__main__":
+ main()
diff --git a/mqsniff.py b/mqsniff.py
new file mode 100644
index 0000000..623c6d7
--- /dev/null
+++ b/mqsniff.py
@@ -0,0 +1,47 @@
+
+import sys
+import uuid
+import logging
+
+import argparse
+from carrot.connection import BrokerConnection
+from carrot.messaging import Publisher, Consumer
+
+parser = argparse.ArgumentParser(description="Read a text stream and send it to an AMQP broker")
+
+parser.add_argument("hostname", help="Hostname of the AMQP broker")
+parser.add_argument("exchange", help="Exchange to use on the AMQP broker")
+parser.add_argument("-v", "--vhost", help="Virtual host to use on the AMQP broker", default="/")
+parser.add_argument("-u", "--user", help="User for the AMQP broker", default="guest")
+parser.add_argument("-p", "--password", help="Password for the AMQP broker", default="guest")
+
+def main():
+ logging.basicConfig(level=logging.INFO)
+ args = parser.parse_args()
+ conn = BrokerConnection(
+ hostname=args.hostname,
+ virtual_host=args.vhost,
+ userid=args.user,
+ password=args.password,
+ )
+ consumer = Consumer(
+ auto_declare = False,
+ connection = conn,
+ exclusive = True,
+ auto_delete = True,
+ )
+ try:
+ logging.info("Creating exchange: %s" % args.exchange)
+ consumer.backend.exchange_declare(exchange=args.exchange, type="topic", durable=False, auto_delete=True)
+ except Exception, e:
+ logging.warning("Failed to create exchange: %s" % e)
+ queue_name = uuid.uuid4().hex
+ logging.info("Creating queue: %s" % queue_name)
+ consumer.backend.queue_declare(queue=queue_name, durable=False, exclusive=True, auto_delete=True)
+ logging.info("Binding queue to exchange: %s" % args.exchange)
+ consumer.backend.queue_bind(queue=queue_name, exchange=args.exchange, routing_key="#")
+ def dump_message(data, msg):
+ print str(data)
+ consumer.register_callback(dump_message)
+ logging.info("Waiting for messages")
+ consumer.wait()
diff --git a/setup.py b/setup.py
index 96a87cb..477f938 100644
--- a/setup.py
+++ b/setup.py
@@ -1,11 +1,11 @@
from setuptools import setup
setup(name='mqtools',
version='0.0.1',
author='Solomon Hykes <[email protected]>',
install_requires=['argparse', 'carrot'],
package_dir = {'mqcat' : '.'},
packages=['mqcat'],
- scripts=['bin/mqcat']
+ scripts=['bin/mqcat', 'bin/mqsniff']
)
|
shykes/mqtools
|
288631cbb7be21cd021f9f0bc0bf9f155893d872
|
Renamed to mqtools and added MIT license
|
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..ed4122c
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,24 @@
+mqtools
+
+Copyright (c) 2009 - 2010 Dotcloud SARL
+
+Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the "Software"), to deal in the Software without
+ restriction, including without limitation the rights to use,
+ copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the
+ Software is furnished to do so, subject to the following
+ conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
diff --git a/setup.py b/setup.py
index 52a76e9..96a87cb 100644
--- a/setup.py
+++ b/setup.py
@@ -1,11 +1,11 @@
from setuptools import setup
-setup(name='mqcat',
+setup(name='mqtools',
version='0.0.1',
author='Solomon Hykes <[email protected]>',
install_requires=['argparse', 'carrot'],
package_dir = {'mqcat' : '.'},
packages=['mqcat'],
scripts=['bin/mqcat']
)
|
shykes/mqtools
|
b1d5f814466190e4c6e2afdec3901529aa731510
|
Fixed executable flags
|
diff --git a/bin/mqcat b/bin/mqcat
old mode 100644
new mode 100755
diff --git a/mqcat.py b/mqcat.py
old mode 100755
new mode 100644
|
shykes/mqtools
|
a98ab9ef63f2e5b000ac10b8f83a652c504451c9
|
Simplified command-line arguments
|
diff --git a/mqcat.py b/mqcat.py
index e6bd207..d6961b3 100755
--- a/mqcat.py
+++ b/mqcat.py
@@ -1,60 +1,59 @@
#!/usr/bin/env python
import sys
import argparse
from carrot.connection import BrokerConnection
from carrot.messaging import Publisher, Consumer
parser = argparse.ArgumentParser(description="Read a text stream and send it to an AMQP broker")
subcommands = parser.add_subparsers(dest="command")
parser_consume = subcommands.add_parser("consume", help="consume amqp messages and write them to stdout")
parser_consume.add_argument("hostname", help="Hostname of the AMQP broker")
-parser_consume.add_argument("--exchange", help="Exchange to use on the AMQP broker")
-parser_consume.add_argument("--queue", help="Queue to use on the AMQP broker")
-parser_consume.add_argument("--key", help="Routing key to use on the AMQP broker", default=None)
+parser_consume.add_argument("queue", help="Queue to use on the AMQP broker")
+parser_consume.add_argument("--exchange", help="Create a fanout exchange and bind it to the queue", default=None)
parser_consume.add_argument("-u", "--user", help="User for the AMQP broker", default=None)
parser_consume.add_argument("-p", "--password", help="Password for the AMQP broker", default=None)
parser_consume.add_argument("-v", "--vhost", help="Virtual host to use on the AMQP broker", default="/")
parser_consume.add_argument("--ack", help="Acknowledge messages, removing them from the queue", action="store_true")
-
parser_send = subcommands.add_parser("send", help="Read lines from stdin, send them to an amqp broker")
parser_send.add_argument("hostname", help="Hostname of the AMQP broker")
-parser_send.add_argument("--exchange", help="Exchange to use on the AMQP broker")
+parser_send.add_argument("exchange", help="Exchange to use on the AMQP broker")
parser_send.add_argument("--key", help="Routing key to use on the AMQP broker")
parser_send.add_argument("-v", "--vhost", help="Virtual host to use on the AMQP broker", default="/")
parser_send.add_argument("-u", "--user", help="User for the AMQP broker", default=None)
parser_send.add_argument("-p", "--password", help="Password for the AMQP broker", default=None)
def main():
args = parser.parse_args()
conn = BrokerConnection(
hostname=args.hostname,
virtual_host=args.vhost,
userid=args.user,
password=args.password,
)
if args.command == "consume":
consumer = Consumer(
connection = conn,
+ exchange_type = "fanout" if args.exchange else None,
exchange = args.exchange,
- queue = args.queue,
- routing_key = args.key
+ queue = args.queue
)
def display_message(data, msg):
print str(data)
if args.ack:
msg.ack()
consumer.register_callback(display_message)
consumer.wait()
elif args.command == "send":
publisher = Publisher(
+ auto_declare = False,
connection = conn,
exchange = args.exchange,
routing_key = args.key
)
for line in sys.stdin.readlines():
publisher.send(line.strip())
publisher.close()
|
shykes/mqtools
|
87cea39f5c600ce992811ebc16cb15b26431b035
|
mqcat: convert text streams to amqp and vice-versa
|
diff --git a/.hgignore b/.hgignore
new file mode 100644
index 0000000..89dba7e
--- /dev/null
+++ b/.hgignore
@@ -0,0 +1,8 @@
+syntax: glob
+
+env/
+*.egg-info
+*.pyc
+pip-log.txt
+dist
+build
diff --git a/__init__.py b/__init__.py
new file mode 100644
index 0000000..d84cade
--- /dev/null
+++ b/__init__.py
@@ -0,0 +1,4 @@
+
+from mqcat import main
+
+__all__ = [main]
diff --git a/bin/mqcat b/bin/mqcat
new file mode 100644
index 0000000..2fba0b0
--- /dev/null
+++ b/bin/mqcat
@@ -0,0 +1,6 @@
+#!/usr/bin/env python
+
+import mqcat
+
+if __name__ == "__main__":
+ mqcat.main()
diff --git a/mqcat.py b/mqcat.py
new file mode 100755
index 0000000..e6bd207
--- /dev/null
+++ b/mqcat.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+
+import sys
+
+import argparse
+from carrot.connection import BrokerConnection
+from carrot.messaging import Publisher, Consumer
+
+parser = argparse.ArgumentParser(description="Read a text stream and send it to an AMQP broker")
+subcommands = parser.add_subparsers(dest="command")
+
+parser_consume = subcommands.add_parser("consume", help="consume amqp messages and write them to stdout")
+parser_consume.add_argument("hostname", help="Hostname of the AMQP broker")
+parser_consume.add_argument("--exchange", help="Exchange to use on the AMQP broker")
+parser_consume.add_argument("--queue", help="Queue to use on the AMQP broker")
+parser_consume.add_argument("--key", help="Routing key to use on the AMQP broker", default=None)
+parser_consume.add_argument("-u", "--user", help="User for the AMQP broker", default=None)
+parser_consume.add_argument("-p", "--password", help="Password for the AMQP broker", default=None)
+parser_consume.add_argument("-v", "--vhost", help="Virtual host to use on the AMQP broker", default="/")
+parser_consume.add_argument("--ack", help="Acknowledge messages, removing them from the queue", action="store_true")
+
+
+parser_send = subcommands.add_parser("send", help="Read lines from stdin, send them to an amqp broker")
+parser_send.add_argument("hostname", help="Hostname of the AMQP broker")
+parser_send.add_argument("--exchange", help="Exchange to use on the AMQP broker")
+parser_send.add_argument("--key", help="Routing key to use on the AMQP broker")
+parser_send.add_argument("-v", "--vhost", help="Virtual host to use on the AMQP broker", default="/")
+parser_send.add_argument("-u", "--user", help="User for the AMQP broker", default=None)
+parser_send.add_argument("-p", "--password", help="Password for the AMQP broker", default=None)
+
+def main():
+ args = parser.parse_args()
+ conn = BrokerConnection(
+ hostname=args.hostname,
+ virtual_host=args.vhost,
+ userid=args.user,
+ password=args.password,
+ )
+ if args.command == "consume":
+ consumer = Consumer(
+ connection = conn,
+ exchange = args.exchange,
+ queue = args.queue,
+ routing_key = args.key
+ )
+ def display_message(data, msg):
+ print str(data)
+ if args.ack:
+ msg.ack()
+ consumer.register_callback(display_message)
+ consumer.wait()
+ elif args.command == "send":
+ publisher = Publisher(
+ connection = conn,
+ exchange = args.exchange,
+ routing_key = args.key
+ )
+ for line in sys.stdin.readlines():
+ publisher.send(line.strip())
+ publisher.close()
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..52a76e9
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,11 @@
+
+from setuptools import setup
+
+setup(name='mqcat',
+ version='0.0.1',
+ author='Solomon Hykes <[email protected]>',
+ install_requires=['argparse', 'carrot'],
+ package_dir = {'mqcat' : '.'},
+ packages=['mqcat'],
+ scripts=['bin/mqcat']
+)
|
rtucker/rgeoutages
|
a4e0af504935a186e8cb873c8dc0c8b737c0287d
|
set markerCluster maxZoom to 14
|
diff --git a/generate_map.py b/generate_map.py
index a2c45b0..48416cd 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,507 +1,509 @@
#!/usr/bin/python
# vim: set fileencoding=utf-8 :
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
from datetime import datetime
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
import scrape_rge
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache2)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache2
(town text, location text, streetname text, latitude real,
longitude real, formattedaddress text, locationtype text,
lastcheck integer, viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location, street):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
if location:
location = location.lower().strip()
else:
location = town
street = street.lower().strip()
# disambiguate lanes
if street.endswith(' la'):
street += 'ne'
using_cache = False
# check the db
c = db.cursor()
c.execute("""select latitude, longitude, formattedaddress, locationtype,
viewport, lastcheck
from geocodecache2
where town=? and location=? and streetname=?
order by lastcheck desc limit 1""",
(town, location, street))
rows = c.fetchall()
if rows:
(latitude, longitude, formattedaddress, locationtype, viewport_json,
lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(street + ", " + location + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute("""insert into geocodecache2
(town, location, streetname, latitude, longitude,
formattedaddress, locationtype, lastcheck,
viewport)
values (?,?,?,?,?,?,?,?,?)""",
(town, location, street, fetchresult['latitude'],
fetchresult['longitude'], fetchresult['formattedaddress'],
fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 30:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 8:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 29:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
return u"""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="900"/>
<title>({len_markers}) Rochester, New York Power Outage Map</title>
<style type="text/css">
v\:* {{behavior:url(#default#VML);}}
html, body {{width: 100%; height: 100%}}
body {{margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}}
p, li {{
font-family: Verdana, sans-serif;
font-size: 13px;
}}
a {{
text-decoration: none;
}}
.hidden {{ visibility: hidden; }}
.unhidden {{ visibility: visible; }}
</style>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3&key={apikey}&sensor=false"></script>
<script type="text/javascript" src="markerclusterer.js"></script>
<script type="text/javascript">
function hide(divID) {{
var item = document.getElementById(divID);
if (item) {{
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}}
}}
function unhide(divID) {{
var item = document.getElementById(divID);
if (item) {{
item.className=(item.className=='hidden')?'unhidden':'hidden';
}}
}}
// aka createMarker
function cMkr(map, iw, lat, lng, title, text, color) {{
// Returns a Marker object at a given position, with a
// descriptive infowindow.
var marker = new google.maps.Marker({{
title: title,
position: new google.maps.LatLng(lat, lng),
icon: "//www.google.com/mapfiles/marker_" + color + ".png"
}});
google.maps.event.addListener(marker, "click", function() {{
iw.content = text;
iw.open(map, marker);
}});
return marker;
}}
function setupMarkers(map, iw) {{
// Returns a list of currently-active Markers.
var b = [];
// BEGIN Dynamic Code
{all_markers}
// END Dynamic Code
return b;
}}
/* distance: {distance}
minimum corner: {minLat}, {minLng}
maximum corner: {maxLat}, {maxLng} */
function initialize() {{
// Creates a map and a master infowindow, as well as a
// markerCluster with all active markers.
var map = new google.maps.Map(
document.getElementById("map_canvas"), {{
center: new google.maps.LatLng({centerLat}, {centerLng}),
zoom: {zoom},
mapTypeId: google.maps.MapTypeId.TERRAIN
}});
var infowindow = new google.maps.InfoWindow({{
content: "lorem ipsum"
}});
- var markerCluster = new MarkerClusterer(map, setupMarkers(map, infowindow));
+ var markerCluster = new MarkerClusterer(map, setupMarkers(map, infowindow), {{
+ maxZoom: 14
+ }});
}};
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
""".format(
apikey = apikey,
len_markers = len(markers),
all_markers = '\n'.join(markers),
distance = distance,
minLat = minLat,
minLng = minLng,
maxLat = maxLat,
maxLng = maxLng,
centerLat = centerLat,
centerLng = centerLng,
zoom = zoom,
)
def produceMarker(lat, lng, text, firstreport=-1, streetinfo={}):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
color = 'grey'
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
streetinfo['FirstReported'] = nicetime
# colors available:
# black, brown, green, purple, yellow, grey, orange, white
if age < 15*60:
color = 'white'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
color = 'purple'
elif age < 65*60:
color = 'orange'
elif age < 115*60:
color = 'brown'
else:
color = 'black'
longtext = '<strong>' + text + '</strong><br/>' + '<br/>'.join('%s: %s' % (key, value) for key, value in streetinfo.items())
return 'b.push(new cMkr(map, iw, %f, %f, "%s", "%s", "%s"));' % (lat, lng, text, longtext, color)
def produceMapBody(body):
return u"""
<body>
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
""" + body + """
</body>
</html>"""
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
newjsondict = {}
# fetch the outages
outagedata = scrape_rge.crawl_outages()
for county, countydata in outagedata.items():
newjsondict[county] = {}
towns = countydata['Towns']
for town, towndata in towns.items():
newjsondict[county][town] = {}
locations = towndata['Locations']
count = 0
for location, locationdata in locations.items():
streets = locationdata['Streets']
newjsondict[county][town][location] = {}
for street, streetdata in streets.items():
newjsondict[county][town][location][street] = {}
for key, value in streetdata.items():
newjsondict[county][town][location][street][key] = value
try:
streetinfo = geocode(db, town, location, street)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
if streetinfo['locationtype'] == 'APPROXIMATE':
streetinfo['formattedaddress'] = '%s? (%s)' % (street, streetinfo['formattedaddress'])
newjsondict[county][town][location][street]['geo'] = streetinfo
newjsondict[county][town][location][street]['firstreport'] = firstreport
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport, streetdata))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (street, town, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
citycenter = geocode(db, town, '', '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress'] + ' (%i street%s)' % (count, s)))
localestring = '<strong>%s</strong>: %i street%s' % (town, count, s)
for key, value in towndata.items():
if type(value) is not dict:
localestring += ', %s: %s' % (key, value)
localestring += ' (%.2f%% affected)' % (float(towndata['CustomersWithoutPower']) / float(towndata['TotalCustomers']) * 100.0)
localelist.append(localestring)
# Save json history file
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
# Save json dump file
newjsonfd = open('data.new.json','w')
json.dump(newjsondict, newjsonfd)
newjsonfd.close()
os.rename('data.new.json', 'data.json')
# XXX: DEBUG CODE
if len(sys.argv) > 1 and sys.argv[1] == 'debug':
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache2 where town=? order by lastcheck desc', ("rochester",))
for i, r in enumerate(c.fetchall()):
markerlist.append(produceMarker(r[0], r[1], r[2], i, {'debug': "num %d" % i}))
# XXX: END DEBUG
if len(markerlist) == 1:
s = ''
else:
s = 's'
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist).encode("utf-8"))
bodytext = u"""
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Rochester, New York Power Outage Map</b> as of {asof_time} ({streets} street{s})</b></p>
<p>Automatically generated every 15 minutes. Zoom for more detail.</p>
<p style="font-size:small;"><a href="javascript:unhide('faqbox');">More information about this map</a> |
<a href="javascript:unhide('chartbox');">Outage graph</a> |
<a href="data.json">JSON</a></p>
<p style="font-size:xx-small;">{locales}</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p>This map plots the approximate locations of power outages in Rochester, New York, and is updated every ten minutes. The source data for this map is published by <A HREF="http://www.rge.com/Outages/outageinformation.html">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="https://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
<li><b>This page may be out of date.</b> If in doubt, check the as-of time.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<hr>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<p style="font-size:xx-small;"><a href="https://github.com/rtucker/rgeoutages/commit/{git_version}">Software last modified {git_time}</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(http://munin.sodtech.net/hoopycat.com/framboise/rgeoutages-day.png); width:495px; height:271px;"></div>
</div>
""".format(asof_time = datetime.now().strftime("%A, %d %B %Y at %r"),
streets = len(markerlist),
s = s,
locales = '<br/>'.join(localelist),
git_version = git_version.strip(),
git_time = git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
b7a862b6dc172b510243b3feaeb11390e0fbbbd7
|
Clean up after API v3 update
|
diff --git a/generate_map.py b/generate_map.py
index 9edf79d..a2c45b0 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,469 +1,507 @@
#!/usr/bin/python
# vim: set fileencoding=utf-8 :
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
+from datetime import datetime
+
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
import scrape_rge
+
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache2)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache2
(town text, location text, streetname text, latitude real,
longitude real, formattedaddress text, locationtype text,
lastcheck integer, viewport text)""")
db.commit()
return db
+
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
+
def geocode(db, town, location, street):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
if location:
location = location.lower().strip()
else:
location = town
street = street.lower().strip()
+ # disambiguate lanes
if street.endswith(' la'):
street += 'ne'
using_cache = False
# check the db
c = db.cursor()
- c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache2 where town=? and location=? and streetname=? order by lastcheck desc limit 1', (town, location, street))
+ c.execute("""select latitude, longitude, formattedaddress, locationtype,
+ viewport, lastcheck
+ from geocodecache2
+ where town=? and location=? and streetname=?
+ order by lastcheck desc limit 1""",
+ (town, location, street))
rows = c.fetchall()
if rows:
- (latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
+ (latitude, longitude, formattedaddress, locationtype, viewport_json,
+ lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(street + ", " + location + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
- c.execute('insert into geocodecache2 (town, location, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?,?)', (town, location, street, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
+ c.execute("""insert into geocodecache2
+ (town, location, streetname, latitude, longitude,
+ formattedaddress, locationtype, lastcheck,
+ viewport)
+ values (?,?,?,?,?,?,?,?,?)""",
+ (town, location, street, fetchresult['latitude'],
+ fetchresult['longitude'], fetchresult['formattedaddress'],
+ fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
+
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
+
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
- out = u"""
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
- <head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
- <meta http-equiv="refresh" content="900"/>
- <title>(%i) Rochester, New York Power Outage Map</title>
-<style type="text/css">
- v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
-
- p, li {
- font-family: Verdana, sans-serif;
- font-size: 13px;
- }
-
- a {
- text-decoration: none;
- }
-
- .hidden { visibility: hidden; }
- .unhidden { visibility: visible; }
-
-</style>
-<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3&key=%s&sensor=false"></script>
-<script type="text/javascript" src="markerclusterer.js"></script>
-<script type="text/javascript">
-
- function hide(divID) {
- var item = document.getElementById(divID);
- if (item) {
- item.className=(item.className=='unhidden')?'hidden':'unhidden';
- }
- }
-
- function unhide(divID) {
- var item = document.getElementById(divID);
- if (item) {
- item.className=(item.className=='hidden')?'unhidden':'hidden';
- }
- }
-
- function createMarker(map, infowindow, position, title, text, color) {
- var marker = new google.maps.Marker({
- title: title,
- position: position,
- icon: "//www.google.com/mapfiles/marker_" + color + ".png"
- });
-
- google.maps.event.addListener(marker, "click", function() {
- infowindow.content = text;
- infowindow.open(map, marker);
- });
-
- return marker;
- }
-
-""" % (len(markers), apikey)
-
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 30:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 8:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 29:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
- out += u"""
- function setupMarkers(map, infowindow) {
- var batch = [];
- %s
- return batch;
- }
- """ % '\n'.join(markers)
-
- out += u"""
- /* distance: %.2f
- minimum corner: %.4f, %.4f
- maximum corner: %.4f, %.4f */
- """ % (distance, minLat, minLng, maxLat, maxLng)
-
- out += u"""
- function initialize() {
- var map = new google.maps.Map(
- document.getElementById("map_canvas"), {
- center: new google.maps.LatLng(%.4f, %.4f),
- zoom: %i,
- mapTypeId: google.maps.MapTypeId.TERRAIN
- });
-
- var infowindow = new google.maps.InfoWindow({
- content: "lorem ipsum"
- });
-
- var markerCluster = new MarkerClusterer(map, setupMarkers(map, infowindow));
- };
-
- google.maps.event.addDomListener(window, 'load', initialize);
-
- """ % (centerLat, centerLng, zoom)
- out += u"""
- </script>
- </head>
- """
+ return u"""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
+ <head>
+ <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
+ <meta http-equiv="refresh" content="900"/>
+ <title>({len_markers}) Rochester, New York Power Outage Map</title>
+ <style type="text/css">
+ v\:* {{behavior:url(#default#VML);}}
+ html, body {{width: 100%; height: 100%}}
+ body {{margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}}
+
+ p, li {{
+ font-family: Verdana, sans-serif;
+ font-size: 13px;
+ }}
+
+ a {{
+ text-decoration: none;
+ }}
+
+ .hidden {{ visibility: hidden; }}
+ .unhidden {{ visibility: visible; }}
+
+ </style>
+ <script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3&key={apikey}&sensor=false"></script>
+ <script type="text/javascript" src="markerclusterer.js"></script>
+ <script type="text/javascript">
+
+ function hide(divID) {{
+ var item = document.getElementById(divID);
+ if (item) {{
+ item.className=(item.className=='unhidden')?'hidden':'unhidden';
+ }}
+ }}
+
+ function unhide(divID) {{
+ var item = document.getElementById(divID);
+ if (item) {{
+ item.className=(item.className=='hidden')?'unhidden':'hidden';
+ }}
+ }}
+
+ // aka createMarker
+ function cMkr(map, iw, lat, lng, title, text, color) {{
+ // Returns a Marker object at a given position, with a
+ // descriptive infowindow.
+ var marker = new google.maps.Marker({{
+ title: title,
+ position: new google.maps.LatLng(lat, lng),
+ icon: "//www.google.com/mapfiles/marker_" + color + ".png"
+ }});
+
+ google.maps.event.addListener(marker, "click", function() {{
+ iw.content = text;
+ iw.open(map, marker);
+ }});
+
+ return marker;
+ }}
+
+ function setupMarkers(map, iw) {{
+ // Returns a list of currently-active Markers.
+ var b = [];
+ // BEGIN Dynamic Code
+ {all_markers}
+ // END Dynamic Code
+ return b;
+ }}
+
+ /* distance: {distance}
+ minimum corner: {minLat}, {minLng}
+ maximum corner: {maxLat}, {maxLng} */
+
+ function initialize() {{
+ // Creates a map and a master infowindow, as well as a
+ // markerCluster with all active markers.
+ var map = new google.maps.Map(
+ document.getElementById("map_canvas"), {{
+ center: new google.maps.LatLng({centerLat}, {centerLng}),
+ zoom: {zoom},
+ mapTypeId: google.maps.MapTypeId.TERRAIN
+ }});
+
+ var infowindow = new google.maps.InfoWindow({{
+ content: "lorem ipsum"
+ }});
+
+ var markerCluster = new MarkerClusterer(map, setupMarkers(map, infowindow));
+ }};
+
+ google.maps.event.addDomListener(window, 'load', initialize);
+
+ </script>
+ </head>
+""".format(
+ apikey = apikey,
+ len_markers = len(markers),
+ all_markers = '\n'.join(markers),
+ distance = distance,
+ minLat = minLat,
+ minLng = minLng,
+ maxLat = maxLat,
+ maxLng = maxLng,
+ centerLat = centerLat,
+ centerLng = centerLng,
+ zoom = zoom,
+ )
- return out
def produceMarker(lat, lng, text, firstreport=-1, streetinfo={}):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
color = 'grey'
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
streetinfo['FirstReported'] = nicetime
# colors available:
# black, brown, green, purple, yellow, grey, orange, white
if age < 15*60:
color = 'white'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
color = 'purple'
elif age < 65*60:
color = 'orange'
elif age < 115*60:
color = 'brown'
else:
color = 'black'
- longtext = '<strong>' + text + '</strong><br />' + '<br />'.join('%s: %s' % (key, value) for key, value in streetinfo.items())
- return 'batch.push(new createMarker(map, infowindow, new google.maps.LatLng(%f, %f), "%s", "%s", "%s"));' % (lat, lng, text, longtext, color)
+ longtext = '<strong>' + text + '</strong><br/>' + '<br/>'.join('%s: %s' % (key, value) for key, value in streetinfo.items())
+ return 'b.push(new cMkr(map, iw, %f, %f, "%s", "%s", "%s"));' % (lat, lng, text, longtext, color)
+
def produceMapBody(body):
- return u""" <body>
+ return u"""
+ <body>
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
- %s
+""" + body + """
</body>
-</html>
-""" % body
+</html>"""
+
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
newjsondict = {}
# fetch the outages
outagedata = scrape_rge.crawl_outages()
for county, countydata in outagedata.items():
newjsondict[county] = {}
towns = countydata['Towns']
for town, towndata in towns.items():
newjsondict[county][town] = {}
locations = towndata['Locations']
count = 0
for location, locationdata in locations.items():
streets = locationdata['Streets']
newjsondict[county][town][location] = {}
for street, streetdata in streets.items():
newjsondict[county][town][location][street] = {}
for key, value in streetdata.items():
newjsondict[county][town][location][street][key] = value
try:
streetinfo = geocode(db, town, location, street)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
if streetinfo['locationtype'] == 'APPROXIMATE':
streetinfo['formattedaddress'] = '%s? (%s)' % (street, streetinfo['formattedaddress'])
newjsondict[county][town][location][street]['geo'] = streetinfo
newjsondict[county][town][location][street]['firstreport'] = firstreport
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport, streetdata))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (street, town, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
citycenter = geocode(db, town, '', '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress'] + ' (%i street%s)' % (count, s)))
localestring = '<strong>%s</strong>: %i street%s' % (town, count, s)
for key, value in towndata.items():
if type(value) is not dict:
localestring += ', %s: %s' % (key, value)
localestring += ' (%.2f%% affected)' % (float(towndata['CustomersWithoutPower']) / float(towndata['TotalCustomers']) * 100.0)
localelist.append(localestring)
# Save json history file
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
# Save json dump file
newjsonfd = open('data.new.json','w')
json.dump(newjsondict, newjsonfd)
newjsonfd.close()
os.rename('data.new.json', 'data.json')
# XXX: DEBUG CODE
- if False:
+ if len(sys.argv) > 1 and sys.argv[1] == 'debug':
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache2 where town=? order by lastcheck desc', ("rochester",))
for i, r in enumerate(c.fetchall()):
markerlist.append(produceMarker(r[0], r[1], r[2], i, {'debug': "num %d" % i}))
# XXX: END DEBUG
if len(markerlist) == 1:
s = ''
else:
s = 's'
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist).encode("utf-8"))
bodytext = u"""
- <div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
- <div id="closebutton" style="top:2px; right:2px; position:absolute">
- <a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
- </div>
- <p><b>Rochester-area Power Outage Map</b> as of %s (%i street%s)</b></p>
- <p style="font-size:small;"><a href="javascript:unhide('faqbox');">More information about this map</a> |
- <a href="javascript:unhide('chartbox');">Outage graph</a> |
- <a href="data.json">JSON</a></p>
- <p style="font-size:xx-small;">%s</p>
+ <div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%; opacity:0.8; padding:10px;">
+ <div id="closebutton" style="top:2px; right:2px; position:absolute">
+ <a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
-
- <div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
- <div id="closebutton" style="top:2px; right:2px; position:absolute">
- <a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
- </div>
- <p>This map plots the approximate locations of power outages in Rochester, New York, and is updated every ten minutes. The source data for this map is published by <A HREF="http://www.rge.com/Outages/outageinformation.html">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="https://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
- <p>Some important tips to keep in mind...</p>
- <ul>
- <li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
- <li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
- <li><b>This page may be out of date.</b> This page does not get regenerated if there are no outages. (Pure laziness on my part.) If in doubt, check the as-of time.</li>
- </ul>
- <p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
- <hr>
- <p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
- <p style="font-size:xx-small;"><a href="https://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
+ <p><b>Rochester, New York Power Outage Map</b> as of {asof_time} ({streets} street{s})</b></p>
+ <p>Automatically generated every 15 minutes. Zoom for more detail.</p>
+ <p style="font-size:small;"><a href="javascript:unhide('faqbox');">More information about this map</a> |
+ <a href="javascript:unhide('chartbox');">Outage graph</a> |
+ <a href="data.json">JSON</a></p>
+ <p style="font-size:xx-small;">{locales}</p>
+ </div>
+
+ <div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%; padding:10px;">
+ <div id="closebutton" style="top:2px; right:2px; position:absolute">
+ <a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
-
- <div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
- <div id="closebutton" style="top:2px; right:2px; position:absolute">
- <a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
- </div>
- <div id="graphimage" style="background:url(http://munin.sodtech.net/hoopycat.com/framboise/rgeoutages-day.png); width:495px; height:271px;"></div>
+ <p>This map plots the approximate locations of power outages in Rochester, New York, and is updated every ten minutes. The source data for this map is published by <A HREF="http://www.rge.com/Outages/outageinformation.html">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="https://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
+ <p>Some important tips to keep in mind...</p>
+ <ul>
+ <li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
+ <li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
+ <li><b>This page may be out of date.</b> If in doubt, check the as-of time.</li>
+ </ul>
+ <p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
+ <hr>
+ <p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
+ <p style="font-size:xx-small;"><a href="https://github.com/rtucker/rgeoutages/commit/{git_version}">Software last modified {git_time}</a>.</p>
+ </div>
+
+ <div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
+ <div id="closebutton" style="top:2px; right:2px; position:absolute">
+ <a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
-
- """ % (time.asctime(), len(markerlist), s, '<br/>'.join(localelist), git_version, git_modtime)
+ <div id="graphimage" style="background:url(http://munin.sodtech.net/hoopycat.com/framboise/rgeoutages-day.png); width:495px; height:271px;"></div>
+ </div>
+ """.format(asof_time = datetime.now().strftime("%A, %d %B %Y at %r"),
+ streets = len(markerlist),
+ s = s,
+ locales = '<br/>'.join(localelist),
+ git_version = git_version.strip(),
+ git_time = git_modtime)
sys.stdout.write(produceMapBody(bodytext))
diff --git a/markerclusterer.js b/markerclusterer.js
new file mode 100644
index 0000000..d6c4dce
--- /dev/null
+++ b/markerclusterer.js
@@ -0,0 +1,1310 @@
+// ==ClosureCompiler==
+// @compilation_level ADVANCED_OPTIMIZATIONS
+// @externs_url http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/maps/google_maps_api_v3_3.js
+// ==/ClosureCompiler==
+
+/**
+ * @name MarkerClusterer for Google Maps v3
+ * @version version 1.0.1
+ * @author Luke Mahe
+ * @fileoverview
+ * The library creates and manages per-zoom-level clusters for large amounts of
+ * markers.
+ * <br/>
+ * This is a v3 implementation of the
+ * <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/"
+ * >v2 MarkerClusterer</a>.
+ */
+
+/**
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+/**
+ * A Marker Clusterer that clusters markers.
+ *
+ * @param {google.maps.Map} map The Google map to attach to.
+ * @param {Array.<google.maps.Marker>=} opt_markers Optional markers to add to
+ * the cluster.
+ * @param {Object=} opt_options support the following options:
+ * 'gridSize': (number) The grid size of a cluster in pixels.
+ * 'maxZoom': (number) The maximum zoom level that a marker can be part of a
+ * cluster.
+ * 'zoomOnClick': (boolean) Whether the default behaviour of clicking on a
+ * cluster is to zoom into it.
+ * 'averageCenter': (boolean) Wether the center of each cluster should be
+ * the average of all markers in the cluster.
+ * 'minimumClusterSize': (number) The minimum number of markers to be in a
+ * cluster before the markers are hidden and a count
+ * is shown.
+ * 'styles': (object) An object that has style properties:
+ * 'url': (string) The image url.
+ * 'height': (number) The image height.
+ * 'width': (number) The image width.
+ * 'anchor': (Array) The anchor position of the label text.
+ * 'textColor': (string) The text color.
+ * 'textSize': (number) The text size.
+ * 'backgroundPosition': (string) The position of the backgound x, y.
+ * @constructor
+ * @extends google.maps.OverlayView
+ */
+function MarkerClusterer(map, opt_markers, opt_options) {
+ // MarkerClusterer implements google.maps.OverlayView interface. We use the
+ // extend function to extend MarkerClusterer with google.maps.OverlayView
+ // because it might not always be available when the code is defined so we
+ // look for it at the last possible moment. If it doesn't exist now then
+ // there is no point going ahead :)
+ this.extend(MarkerClusterer, google.maps.OverlayView);
+ this.map_ = map;
+
+ /**
+ * @type {Array.<google.maps.Marker>}
+ * @private
+ */
+ this.markers_ = [];
+
+ /**
+ * @type {Array.<Cluster>}
+ */
+ this.clusters_ = [];
+
+ this.sizes = [53, 56, 66, 78, 90];
+
+ /**
+ * @private
+ */
+ this.styles_ = [];
+
+ /**
+ * @type {boolean}
+ * @private
+ */
+ this.ready_ = false;
+
+ var options = opt_options || {};
+
+ /**
+ * @type {number}
+ * @private
+ */
+ this.gridSize_ = options['gridSize'] || 60;
+
+ /**
+ * @private
+ */
+ this.minClusterSize_ = options['minimumClusterSize'] || 2;
+
+
+ /**
+ * @type {?number}
+ * @private
+ */
+ this.maxZoom_ = options['maxZoom'] || null;
+
+ this.styles_ = options['styles'] || [];
+
+ /**
+ * @type {string}
+ * @private
+ */
+ this.imagePath_ = options['imagePath'] ||
+ this.MARKER_CLUSTER_IMAGE_PATH_;
+
+ /**
+ * @type {string}
+ * @private
+ */
+ this.imageExtension_ = options['imageExtension'] ||
+ this.MARKER_CLUSTER_IMAGE_EXTENSION_;
+
+ /**
+ * @type {boolean}
+ * @private
+ */
+ this.zoomOnClick_ = true;
+
+ if (options['zoomOnClick'] != undefined) {
+ this.zoomOnClick_ = options['zoomOnClick'];
+ }
+
+ /**
+ * @type {boolean}
+ * @private
+ */
+ this.averageCenter_ = false;
+
+ if (options['averageCenter'] != undefined) {
+ this.averageCenter_ = options['averageCenter'];
+ }
+
+ this.setupStyles_();
+
+ this.setMap(map);
+
+ /**
+ * @type {number}
+ * @private
+ */
+ this.prevZoom_ = this.map_.getZoom();
+
+ // Add the map event listeners
+ var that = this;
+ google.maps.event.addListener(this.map_, 'zoom_changed', function() {
+ // Determines map type and prevent illegal zoom levels
+ var zoom = that.map_.getZoom();
+ var minZoom = that.map_.minZoom || 0;
+ var maxZoom = Math.min(that.map_.maxZoom || 100,
+ that.map_.mapTypes[that.map_.getMapTypeId()].maxZoom);
+ zoom = Math.min(Math.max(zoom,minZoom),maxZoom);
+
+ if (that.prevZoom_ != zoom) {
+ that.prevZoom_ = zoom;
+ that.resetViewport();
+ }
+ });
+
+ google.maps.event.addListener(this.map_, 'idle', function() {
+ that.redraw();
+ });
+
+ // Finally, add the markers
+ if (opt_markers && (opt_markers.length || Object.keys(opt_markers).length)) {
+ this.addMarkers(opt_markers, false);
+ }
+}
+
+
+/**
+ * The marker cluster image path.
+ *
+ * @type {string}
+ * @private
+ */
+MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_PATH_ =
+ 'http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/' +
+ 'images/m';
+
+
+/**
+ * The marker cluster image path.
+ *
+ * @type {string}
+ * @private
+ */
+MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_EXTENSION_ = 'png';
+
+
+/**
+ * Extends a objects prototype by anothers.
+ *
+ * @param {Object} obj1 The object to be extended.
+ * @param {Object} obj2 The object to extend with.
+ * @return {Object} The new extended object.
+ * @ignore
+ */
+MarkerClusterer.prototype.extend = function(obj1, obj2) {
+ return (function(object) {
+ for (var property in object.prototype) {
+ this.prototype[property] = object.prototype[property];
+ }
+ return this;
+ }).apply(obj1, [obj2]);
+};
+
+
+/**
+ * Implementaion of the interface method.
+ * @ignore
+ */
+MarkerClusterer.prototype.onAdd = function() {
+ this.setReady_(true);
+};
+
+/**
+ * Implementaion of the interface method.
+ * @ignore
+ */
+MarkerClusterer.prototype.draw = function() {};
+
+/**
+ * Sets up the styles object.
+ *
+ * @private
+ */
+MarkerClusterer.prototype.setupStyles_ = function() {
+ if (this.styles_.length) {
+ return;
+ }
+
+ for (var i = 0, size; size = this.sizes[i]; i++) {
+ this.styles_.push({
+ url: this.imagePath_ + (i + 1) + '.' + this.imageExtension_,
+ height: size,
+ width: size
+ });
+ }
+};
+
+/**
+ * Fit the map to the bounds of the markers in the clusterer.
+ */
+MarkerClusterer.prototype.fitMapToMarkers = function() {
+ var markers = this.getMarkers();
+ var bounds = new google.maps.LatLngBounds();
+ for (var i = 0, marker; marker = markers[i]; i++) {
+ bounds.extend(marker.getPosition());
+ }
+
+ this.map_.fitBounds(bounds);
+};
+
+
+/**
+ * Sets the styles.
+ *
+ * @param {Object} styles The style to set.
+ */
+MarkerClusterer.prototype.setStyles = function(styles) {
+ this.styles_ = styles;
+};
+
+
+/**
+ * Gets the styles.
+ *
+ * @return {Object} The styles object.
+ */
+MarkerClusterer.prototype.getStyles = function() {
+ return this.styles_;
+};
+
+
+/**
+ * Whether zoom on click is set.
+ *
+ * @return {boolean} True if zoomOnClick_ is set.
+ */
+MarkerClusterer.prototype.isZoomOnClick = function() {
+ return this.zoomOnClick_;
+};
+
+/**
+ * Whether average center is set.
+ *
+ * @return {boolean} True if averageCenter_ is set.
+ */
+MarkerClusterer.prototype.isAverageCenter = function() {
+ return this.averageCenter_;
+};
+
+
+/**
+ * Returns the array of markers in the clusterer.
+ *
+ * @return {Array.<google.maps.Marker>} The markers.
+ */
+MarkerClusterer.prototype.getMarkers = function() {
+ return this.markers_;
+};
+
+
+/**
+ * Returns the number of markers in the clusterer
+ *
+ * @return {Number} The number of markers.
+ */
+MarkerClusterer.prototype.getTotalMarkers = function() {
+ return this.markers_.length;
+};
+
+
+/**
+ * Sets the max zoom for the clusterer.
+ *
+ * @param {number} maxZoom The max zoom level.
+ */
+MarkerClusterer.prototype.setMaxZoom = function(maxZoom) {
+ this.maxZoom_ = maxZoom;
+};
+
+
+/**
+ * Gets the max zoom for the clusterer.
+ *
+ * @return {number} The max zoom level.
+ */
+MarkerClusterer.prototype.getMaxZoom = function() {
+ return this.maxZoom_;
+};
+
+
+/**
+ * The function for calculating the cluster icon image.
+ *
+ * @param {Array.<google.maps.Marker>} markers The markers in the clusterer.
+ * @param {number} numStyles The number of styles available.
+ * @return {Object} A object properties: 'text' (string) and 'index' (number).
+ * @private
+ */
+MarkerClusterer.prototype.calculator_ = function(markers, numStyles) {
+ var index = 0;
+ var count = markers.length;
+ var dv = count;
+ while (dv !== 0) {
+ dv = parseInt(dv / 10, 10);
+ index++;
+ }
+
+ index = Math.min(index, numStyles);
+ return {
+ text: count,
+ index: index
+ };
+};
+
+
+/**
+ * Set the calculator function.
+ *
+ * @param {function(Array, number)} calculator The function to set as the
+ * calculator. The function should return a object properties:
+ * 'text' (string) and 'index' (number).
+ *
+ */
+MarkerClusterer.prototype.setCalculator = function(calculator) {
+ this.calculator_ = calculator;
+};
+
+
+/**
+ * Get the calculator function.
+ *
+ * @return {function(Array, number)} the calculator function.
+ */
+MarkerClusterer.prototype.getCalculator = function() {
+ return this.calculator_;
+};
+
+
+/**
+ * Add an array of markers to the clusterer.
+ *
+ * @param {Array.<google.maps.Marker>} markers The markers to add.
+ * @param {boolean=} opt_nodraw Whether to redraw the clusters.
+ */
+MarkerClusterer.prototype.addMarkers = function(markers, opt_nodraw) {
+ if (markers.length) {
+ for (var i = 0, marker; marker = markers[i]; i++) {
+ this.pushMarkerTo_(marker);
+ }
+ } else if (Object.keys(markers).length) {
+ for (var marker in markers) {
+ this.pushMarkerTo_(markers[marker]);
+ }
+ }
+ if (!opt_nodraw) {
+ this.redraw();
+ }
+};
+
+
+/**
+ * Pushes a marker to the clusterer.
+ *
+ * @param {google.maps.Marker} marker The marker to add.
+ * @private
+ */
+MarkerClusterer.prototype.pushMarkerTo_ = function(marker) {
+ marker.isAdded = false;
+ if (marker['draggable']) {
+ // If the marker is draggable add a listener so we update the clusters on
+ // the drag end.
+ var that = this;
+ google.maps.event.addListener(marker, 'dragend', function() {
+ marker.isAdded = false;
+ that.repaint();
+ });
+ }
+ this.markers_.push(marker);
+};
+
+
+/**
+ * Adds a marker to the clusterer and redraws if needed.
+ *
+ * @param {google.maps.Marker} marker The marker to add.
+ * @param {boolean=} opt_nodraw Whether to redraw the clusters.
+ */
+MarkerClusterer.prototype.addMarker = function(marker, opt_nodraw) {
+ this.pushMarkerTo_(marker);
+ if (!opt_nodraw) {
+ this.redraw();
+ }
+};
+
+
+/**
+ * Removes a marker and returns true if removed, false if not
+ *
+ * @param {google.maps.Marker} marker The marker to remove
+ * @return {boolean} Whether the marker was removed or not
+ * @private
+ */
+MarkerClusterer.prototype.removeMarker_ = function(marker) {
+ var index = -1;
+ if (this.markers_.indexOf) {
+ index = this.markers_.indexOf(marker);
+ } else {
+ for (var i = 0, m; m = this.markers_[i]; i++) {
+ if (m == marker) {
+ index = i;
+ break;
+ }
+ }
+ }
+
+ if (index == -1) {
+ // Marker is not in our list of markers.
+ return false;
+ }
+
+ marker.setMap(null);
+
+ this.markers_.splice(index, 1);
+
+ return true;
+};
+
+
+/**
+ * Remove a marker from the cluster.
+ *
+ * @param {google.maps.Marker} marker The marker to remove.
+ * @param {boolean=} opt_nodraw Optional boolean to force no redraw.
+ * @return {boolean} True if the marker was removed.
+ */
+MarkerClusterer.prototype.removeMarker = function(marker, opt_nodraw) {
+ var removed = this.removeMarker_(marker);
+
+ if (!opt_nodraw && removed) {
+ this.resetViewport();
+ this.redraw();
+ return true;
+ } else {
+ return false;
+ }
+};
+
+
+/**
+ * Removes an array of markers from the cluster.
+ *
+ * @param {Array.<google.maps.Marker>} markers The markers to remove.
+ * @param {boolean=} opt_nodraw Optional boolean to force no redraw.
+ */
+MarkerClusterer.prototype.removeMarkers = function(markers, opt_nodraw) {
+ var removed = false;
+
+ for (var i = 0, marker; marker = markers[i]; i++) {
+ var r = this.removeMarker_(marker);
+ removed = removed || r;
+ }
+
+ if (!opt_nodraw && removed) {
+ this.resetViewport();
+ this.redraw();
+ return true;
+ }
+};
+
+
+/**
+ * Sets the clusterer's ready state.
+ *
+ * @param {boolean} ready The state.
+ * @private
+ */
+MarkerClusterer.prototype.setReady_ = function(ready) {
+ if (!this.ready_) {
+ this.ready_ = ready;
+ this.createClusters_();
+ }
+};
+
+
+/**
+ * Returns the number of clusters in the clusterer.
+ *
+ * @return {number} The number of clusters.
+ */
+MarkerClusterer.prototype.getTotalClusters = function() {
+ return this.clusters_.length;
+};
+
+
+/**
+ * Returns the google map that the clusterer is associated with.
+ *
+ * @return {google.maps.Map} The map.
+ */
+MarkerClusterer.prototype.getMap = function() {
+ return this.map_;
+};
+
+
+/**
+ * Sets the google map that the clusterer is associated with.
+ *
+ * @param {google.maps.Map} map The map.
+ */
+MarkerClusterer.prototype.setMap = function(map) {
+ this.map_ = map;
+};
+
+
+/**
+ * Returns the size of the grid.
+ *
+ * @return {number} The grid size.
+ */
+MarkerClusterer.prototype.getGridSize = function() {
+ return this.gridSize_;
+};
+
+
+/**
+ * Sets the size of the grid.
+ *
+ * @param {number} size The grid size.
+ */
+MarkerClusterer.prototype.setGridSize = function(size) {
+ this.gridSize_ = size;
+};
+
+
+/**
+ * Returns the min cluster size.
+ *
+ * @return {number} The grid size.
+ */
+MarkerClusterer.prototype.getMinClusterSize = function() {
+ return this.minClusterSize_;
+};
+
+/**
+ * Sets the min cluster size.
+ *
+ * @param {number} size The grid size.
+ */
+MarkerClusterer.prototype.setMinClusterSize = function(size) {
+ this.minClusterSize_ = size;
+};
+
+
+/**
+ * Extends a bounds object by the grid size.
+ *
+ * @param {google.maps.LatLngBounds} bounds The bounds to extend.
+ * @return {google.maps.LatLngBounds} The extended bounds.
+ */
+MarkerClusterer.prototype.getExtendedBounds = function(bounds) {
+ var projection = this.getProjection();
+
+ // Turn the bounds into latlng.
+ var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),
+ bounds.getNorthEast().lng());
+ var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),
+ bounds.getSouthWest().lng());
+
+ // Convert the points to pixels and the extend out by the grid size.
+ var trPix = projection.fromLatLngToDivPixel(tr);
+ trPix.x += this.gridSize_;
+ trPix.y -= this.gridSize_;
+
+ var blPix = projection.fromLatLngToDivPixel(bl);
+ blPix.x -= this.gridSize_;
+ blPix.y += this.gridSize_;
+
+ // Convert the pixel points back to LatLng
+ var ne = projection.fromDivPixelToLatLng(trPix);
+ var sw = projection.fromDivPixelToLatLng(blPix);
+
+ // Extend the bounds to contain the new bounds.
+ bounds.extend(ne);
+ bounds.extend(sw);
+
+ return bounds;
+};
+
+
+/**
+ * Determins if a marker is contained in a bounds.
+ *
+ * @param {google.maps.Marker} marker The marker to check.
+ * @param {google.maps.LatLngBounds} bounds The bounds to check against.
+ * @return {boolean} True if the marker is in the bounds.
+ * @private
+ */
+MarkerClusterer.prototype.isMarkerInBounds_ = function(marker, bounds) {
+ return bounds.contains(marker.getPosition());
+};
+
+
+/**
+ * Clears all clusters and markers from the clusterer.
+ */
+MarkerClusterer.prototype.clearMarkers = function() {
+ this.resetViewport(true);
+
+ // Set the markers a empty array.
+ this.markers_ = [];
+};
+
+
+/**
+ * Clears all existing clusters and recreates them.
+ * @param {boolean} opt_hide To also hide the marker.
+ */
+MarkerClusterer.prototype.resetViewport = function(opt_hide) {
+ // Remove all the clusters
+ for (var i = 0, cluster; cluster = this.clusters_[i]; i++) {
+ cluster.remove();
+ }
+
+ // Reset the markers to not be added and to be invisible.
+ for (var i = 0, marker; marker = this.markers_[i]; i++) {
+ marker.isAdded = false;
+ if (opt_hide) {
+ marker.setMap(null);
+ }
+ }
+
+ this.clusters_ = [];
+};
+
+/**
+ *
+ */
+MarkerClusterer.prototype.repaint = function() {
+ var oldClusters = this.clusters_.slice();
+ this.clusters_.length = 0;
+ this.resetViewport();
+ this.redraw();
+
+ // Remove the old clusters.
+ // Do it in a timeout so the other clusters have been drawn first.
+ window.setTimeout(function() {
+ for (var i = 0, cluster; cluster = oldClusters[i]; i++) {
+ cluster.remove();
+ }
+ }, 0);
+};
+
+
+/**
+ * Redraws the clusters.
+ */
+MarkerClusterer.prototype.redraw = function() {
+ this.createClusters_();
+};
+
+
+/**
+ * Calculates the distance between two latlng locations in km.
+ * @see http://www.movable-type.co.uk/scripts/latlong.html
+ *
+ * @param {google.maps.LatLng} p1 The first lat lng point.
+ * @param {google.maps.LatLng} p2 The second lat lng point.
+ * @return {number} The distance between the two points in km.
+ * @private
+*/
+MarkerClusterer.prototype.distanceBetweenPoints_ = function(p1, p2) {
+ if (!p1 || !p2) {
+ return 0;
+ }
+
+ var R = 6371; // Radius of the Earth in km
+ var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
+ var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
+ var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
+ Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
+ Math.sin(dLon / 2) * Math.sin(dLon / 2);
+ var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
+ var d = R * c;
+ return d;
+};
+
+
+/**
+ * Add a marker to a cluster, or creates a new cluster.
+ *
+ * @param {google.maps.Marker} marker The marker to add.
+ * @private
+ */
+MarkerClusterer.prototype.addToClosestCluster_ = function(marker) {
+ var distance = 40000; // Some large number
+ var clusterToAddTo = null;
+ var pos = marker.getPosition();
+ for (var i = 0, cluster; cluster = this.clusters_[i]; i++) {
+ var center = cluster.getCenter();
+ if (center) {
+ var d = this.distanceBetweenPoints_(center, marker.getPosition());
+ if (d < distance) {
+ distance = d;
+ clusterToAddTo = cluster;
+ }
+ }
+ }
+
+ if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
+ clusterToAddTo.addMarker(marker);
+ } else {
+ var cluster = new Cluster(this);
+ cluster.addMarker(marker);
+ this.clusters_.push(cluster);
+ }
+};
+
+
+/**
+ * Creates the clusters.
+ *
+ * @private
+ */
+MarkerClusterer.prototype.createClusters_ = function() {
+ if (!this.ready_) {
+ return;
+ }
+
+ // Get our current map view bounds.
+ // Create a new bounds object so we don't affect the map.
+ var mapBounds = new google.maps.LatLngBounds(this.map_.getBounds().getSouthWest(),
+ this.map_.getBounds().getNorthEast());
+ var bounds = this.getExtendedBounds(mapBounds);
+
+ for (var i = 0, marker; marker = this.markers_[i]; i++) {
+ if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
+ this.addToClosestCluster_(marker);
+ }
+ }
+};
+
+
+/**
+ * A cluster that contains markers.
+ *
+ * @param {MarkerClusterer} markerClusterer The markerclusterer that this
+ * cluster is associated with.
+ * @constructor
+ * @ignore
+ */
+function Cluster(markerClusterer) {
+ this.markerClusterer_ = markerClusterer;
+ this.map_ = markerClusterer.getMap();
+ this.gridSize_ = markerClusterer.getGridSize();
+ this.minClusterSize_ = markerClusterer.getMinClusterSize();
+ this.averageCenter_ = markerClusterer.isAverageCenter();
+ this.center_ = null;
+ this.markers_ = [];
+ this.bounds_ = null;
+ this.clusterIcon_ = new ClusterIcon(this, markerClusterer.getStyles(),
+ markerClusterer.getGridSize());
+}
+
+/**
+ * Determins if a marker is already added to the cluster.
+ *
+ * @param {google.maps.Marker} marker The marker to check.
+ * @return {boolean} True if the marker is already added.
+ */
+Cluster.prototype.isMarkerAlreadyAdded = function(marker) {
+ if (this.markers_.indexOf) {
+ return this.markers_.indexOf(marker) != -1;
+ } else {
+ for (var i = 0, m; m = this.markers_[i]; i++) {
+ if (m == marker) {
+ return true;
+ }
+ }
+ }
+ return false;
+};
+
+
+/**
+ * Add a marker the cluster.
+ *
+ * @param {google.maps.Marker} marker The marker to add.
+ * @return {boolean} True if the marker was added.
+ */
+Cluster.prototype.addMarker = function(marker) {
+ if (this.isMarkerAlreadyAdded(marker)) {
+ return false;
+ }
+
+ if (!this.center_) {
+ this.center_ = marker.getPosition();
+ this.calculateBounds_();
+ } else {
+ if (this.averageCenter_) {
+ var l = this.markers_.length + 1;
+ var lat = (this.center_.lat() * (l-1) + marker.getPosition().lat()) / l;
+ var lng = (this.center_.lng() * (l-1) + marker.getPosition().lng()) / l;
+ this.center_ = new google.maps.LatLng(lat, lng);
+ this.calculateBounds_();
+ }
+ }
+
+ marker.isAdded = true;
+ this.markers_.push(marker);
+
+ var len = this.markers_.length;
+ if (len < this.minClusterSize_ && marker.getMap() != this.map_) {
+ // Min cluster size not reached so show the marker.
+ marker.setMap(this.map_);
+ }
+
+ if (len == this.minClusterSize_) {
+ // Hide the markers that were showing.
+ for (var i = 0; i < len; i++) {
+ this.markers_[i].setMap(null);
+ }
+ }
+
+ if (len >= this.minClusterSize_) {
+ marker.setMap(null);
+ }
+
+ this.updateIcon();
+ return true;
+};
+
+
+/**
+ * Returns the marker clusterer that the cluster is associated with.
+ *
+ * @return {MarkerClusterer} The associated marker clusterer.
+ */
+Cluster.prototype.getMarkerClusterer = function() {
+ return this.markerClusterer_;
+};
+
+
+/**
+ * Returns the bounds of the cluster.
+ *
+ * @return {google.maps.LatLngBounds} the cluster bounds.
+ */
+Cluster.prototype.getBounds = function() {
+ var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
+ var markers = this.getMarkers();
+ for (var i = 0, marker; marker = markers[i]; i++) {
+ bounds.extend(marker.getPosition());
+ }
+ return bounds;
+};
+
+
+/**
+ * Removes the cluster
+ */
+Cluster.prototype.remove = function() {
+ this.clusterIcon_.remove();
+ this.markers_.length = 0;
+ delete this.markers_;
+};
+
+
+/**
+ * Returns the center of the cluster.
+ *
+ * @return {number} The cluster center.
+ */
+Cluster.prototype.getSize = function() {
+ return this.markers_.length;
+};
+
+
+/**
+ * Returns the center of the cluster.
+ *
+ * @return {Array.<google.maps.Marker>} The cluster center.
+ */
+Cluster.prototype.getMarkers = function() {
+ return this.markers_;
+};
+
+
+/**
+ * Returns the center of the cluster.
+ *
+ * @return {google.maps.LatLng} The cluster center.
+ */
+Cluster.prototype.getCenter = function() {
+ return this.center_;
+};
+
+
+/**
+ * Calculated the extended bounds of the cluster with the grid.
+ *
+ * @private
+ */
+Cluster.prototype.calculateBounds_ = function() {
+ var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
+ this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds);
+};
+
+
+/**
+ * Determines if a marker lies in the clusters bounds.
+ *
+ * @param {google.maps.Marker} marker The marker to check.
+ * @return {boolean} True if the marker lies in the bounds.
+ */
+Cluster.prototype.isMarkerInClusterBounds = function(marker) {
+ return this.bounds_.contains(marker.getPosition());
+};
+
+
+/**
+ * Returns the map that the cluster is associated with.
+ *
+ * @return {google.maps.Map} The map.
+ */
+Cluster.prototype.getMap = function() {
+ return this.map_;
+};
+
+
+/**
+ * Updates the cluster icon
+ */
+Cluster.prototype.updateIcon = function() {
+ var zoom = this.map_.getZoom();
+ var mz = this.markerClusterer_.getMaxZoom();
+
+ if (mz && zoom > mz) {
+ // The zoom is greater than our max zoom so show all the markers in cluster.
+ for (var i = 0, marker; marker = this.markers_[i]; i++) {
+ marker.setMap(this.map_);
+ }
+ return;
+ }
+
+ if (this.markers_.length < this.minClusterSize_) {
+ // Min cluster size not yet reached.
+ this.clusterIcon_.hide();
+ return;
+ }
+
+ var numStyles = this.markerClusterer_.getStyles().length;
+ var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles);
+ this.clusterIcon_.setCenter(this.center_);
+ this.clusterIcon_.setSums(sums);
+ this.clusterIcon_.show();
+};
+
+
+/**
+ * A cluster icon
+ *
+ * @param {Cluster} cluster The cluster to be associated with.
+ * @param {Object} styles An object that has style properties:
+ * 'url': (string) The image url.
+ * 'height': (number) The image height.
+ * 'width': (number) The image width.
+ * 'anchor': (Array) The anchor position of the label text.
+ * 'textColor': (string) The text color.
+ * 'textSize': (number) The text size.
+ * 'backgroundPosition: (string) The background postition x, y.
+ * @param {number=} opt_padding Optional padding to apply to the cluster icon.
+ * @constructor
+ * @extends google.maps.OverlayView
+ * @ignore
+ */
+function ClusterIcon(cluster, styles, opt_padding) {
+ cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView);
+
+ this.styles_ = styles;
+ this.padding_ = opt_padding || 0;
+ this.cluster_ = cluster;
+ this.center_ = null;
+ this.map_ = cluster.getMap();
+ this.div_ = null;
+ this.sums_ = null;
+ this.visible_ = false;
+
+ this.setMap(this.map_);
+}
+
+
+/**
+ * Triggers the clusterclick event and zoom's if the option is set.
+ */
+ClusterIcon.prototype.triggerClusterClick = function() {
+ var markerClusterer = this.cluster_.getMarkerClusterer();
+
+ // Trigger the clusterclick event.
+ google.maps.event.trigger(markerClusterer, 'clusterclick', this.cluster_);
+
+ if (markerClusterer.isZoomOnClick()) {
+ // Zoom into the cluster.
+ this.map_.fitBounds(this.cluster_.getBounds());
+ }
+};
+
+
+/**
+ * Adding the cluster icon to the dom.
+ * @ignore
+ */
+ClusterIcon.prototype.onAdd = function() {
+ this.div_ = document.createElement('DIV');
+ if (this.visible_) {
+ var pos = this.getPosFromLatLng_(this.center_);
+ this.div_.style.cssText = this.createCss(pos);
+ this.div_.innerHTML = this.sums_.text;
+ }
+
+ var panes = this.getPanes();
+ panes.overlayMouseTarget.appendChild(this.div_);
+
+ var that = this;
+ google.maps.event.addDomListener(this.div_, 'click', function() {
+ that.triggerClusterClick();
+ });
+};
+
+
+/**
+ * Returns the position to place the div dending on the latlng.
+ *
+ * @param {google.maps.LatLng} latlng The position in latlng.
+ * @return {google.maps.Point} The position in pixels.
+ * @private
+ */
+ClusterIcon.prototype.getPosFromLatLng_ = function(latlng) {
+ var pos = this.getProjection().fromLatLngToDivPixel(latlng);
+ pos.x -= parseInt(this.width_ / 2, 10);
+ pos.y -= parseInt(this.height_ / 2, 10);
+ return pos;
+};
+
+
+/**
+ * Draw the icon.
+ * @ignore
+ */
+ClusterIcon.prototype.draw = function() {
+ if (this.visible_) {
+ var pos = this.getPosFromLatLng_(this.center_);
+ this.div_.style.top = pos.y + 'px';
+ this.div_.style.left = pos.x + 'px';
+ }
+};
+
+
+/**
+ * Hide the icon.
+ */
+ClusterIcon.prototype.hide = function() {
+ if (this.div_) {
+ this.div_.style.display = 'none';
+ }
+ this.visible_ = false;
+};
+
+
+/**
+ * Position and show the icon.
+ */
+ClusterIcon.prototype.show = function() {
+ if (this.div_) {
+ var pos = this.getPosFromLatLng_(this.center_);
+ this.div_.style.cssText = this.createCss(pos);
+ this.div_.style.display = '';
+ }
+ this.visible_ = true;
+};
+
+
+/**
+ * Remove the icon from the map
+ */
+ClusterIcon.prototype.remove = function() {
+ this.setMap(null);
+};
+
+
+/**
+ * Implementation of the onRemove interface.
+ * @ignore
+ */
+ClusterIcon.prototype.onRemove = function() {
+ if (this.div_ && this.div_.parentNode) {
+ this.hide();
+ this.div_.parentNode.removeChild(this.div_);
+ this.div_ = null;
+ }
+};
+
+
+/**
+ * Set the sums of the icon.
+ *
+ * @param {Object} sums The sums containing:
+ * 'text': (string) The text to display in the icon.
+ * 'index': (number) The style index of the icon.
+ */
+ClusterIcon.prototype.setSums = function(sums) {
+ this.sums_ = sums;
+ this.text_ = sums.text;
+ this.index_ = sums.index;
+ if (this.div_) {
+ this.div_.innerHTML = sums.text;
+ }
+
+ this.useStyle();
+};
+
+
+/**
+ * Sets the icon to the the styles.
+ */
+ClusterIcon.prototype.useStyle = function() {
+ var index = Math.max(0, this.sums_.index - 1);
+ index = Math.min(this.styles_.length - 1, index);
+ var style = this.styles_[index];
+ this.url_ = style['url'];
+ this.height_ = style['height'];
+ this.width_ = style['width'];
+ this.textColor_ = style['textColor'];
+ this.anchor_ = style['anchor'];
+ this.textSize_ = style['textSize'];
+ this.backgroundPosition_ = style['backgroundPosition'];
+};
+
+
+/**
+ * Sets the center of the icon.
+ *
+ * @param {google.maps.LatLng} center The latlng to set as the center.
+ */
+ClusterIcon.prototype.setCenter = function(center) {
+ this.center_ = center;
+};
+
+
+/**
+ * Create the css text based on the position of the icon.
+ *
+ * @param {google.maps.Point} pos The position.
+ * @return {string} The css style text.
+ */
+ClusterIcon.prototype.createCss = function(pos) {
+ var style = [];
+ style.push('background-image:url(' + this.url_ + ');');
+ var backgroundPosition = this.backgroundPosition_ ? this.backgroundPosition_ : '0 0';
+ style.push('background-position:' + backgroundPosition + ';');
+
+ if (typeof this.anchor_ === 'object') {
+ if (typeof this.anchor_[0] === 'number' && this.anchor_[0] > 0 &&
+ this.anchor_[0] < this.height_) {
+ style.push('height:' + (this.height_ - this.anchor_[0]) +
+ 'px; padding-top:' + this.anchor_[0] + 'px;');
+ } else {
+ style.push('height:' + this.height_ + 'px; line-height:' + this.height_ +
+ 'px;');
+ }
+ if (typeof this.anchor_[1] === 'number' && this.anchor_[1] > 0 &&
+ this.anchor_[1] < this.width_) {
+ style.push('width:' + (this.width_ - this.anchor_[1]) +
+ 'px; padding-left:' + this.anchor_[1] + 'px;');
+ } else {
+ style.push('width:' + this.width_ + 'px; text-align:center;');
+ }
+ } else {
+ style.push('height:' + this.height_ + 'px; line-height:' +
+ this.height_ + 'px; width:' + this.width_ + 'px; text-align:center;');
+ }
+
+ var txtColor = this.textColor_ ? this.textColor_ : 'black';
+ var txtSize = this.textSize_ ? this.textSize_ : 11;
+
+ style.push('cursor:pointer; top:' + pos.y + 'px; left:' +
+ pos.x + 'px; color:' + txtColor + '; position:absolute; font-size:' +
+ txtSize + 'px; font-family:Arial,sans-serif; font-weight:bold');
+ return style.join('');
+};
+
+
+// Export Symbols for Closure
+// If you are not going to compile with closure then you can remove the
+// code below.
+window['MarkerClusterer'] = MarkerClusterer;
+MarkerClusterer.prototype['addMarker'] = MarkerClusterer.prototype.addMarker;
+MarkerClusterer.prototype['addMarkers'] = MarkerClusterer.prototype.addMarkers;
+MarkerClusterer.prototype['clearMarkers'] =
+ MarkerClusterer.prototype.clearMarkers;
+MarkerClusterer.prototype['fitMapToMarkers'] =
+ MarkerClusterer.prototype.fitMapToMarkers;
+MarkerClusterer.prototype['getCalculator'] =
+ MarkerClusterer.prototype.getCalculator;
+MarkerClusterer.prototype['getGridSize'] =
+ MarkerClusterer.prototype.getGridSize;
+MarkerClusterer.prototype['getExtendedBounds'] =
+ MarkerClusterer.prototype.getExtendedBounds;
+MarkerClusterer.prototype['getMap'] = MarkerClusterer.prototype.getMap;
+MarkerClusterer.prototype['getMarkers'] = MarkerClusterer.prototype.getMarkers;
+MarkerClusterer.prototype['getMaxZoom'] = MarkerClusterer.prototype.getMaxZoom;
+MarkerClusterer.prototype['getStyles'] = MarkerClusterer.prototype.getStyles;
+MarkerClusterer.prototype['getTotalClusters'] =
+ MarkerClusterer.prototype.getTotalClusters;
+MarkerClusterer.prototype['getTotalMarkers'] =
+ MarkerClusterer.prototype.getTotalMarkers;
+MarkerClusterer.prototype['redraw'] = MarkerClusterer.prototype.redraw;
+MarkerClusterer.prototype['removeMarker'] =
+ MarkerClusterer.prototype.removeMarker;
+MarkerClusterer.prototype['removeMarkers'] =
+ MarkerClusterer.prototype.removeMarkers;
+MarkerClusterer.prototype['resetViewport'] =
+ MarkerClusterer.prototype.resetViewport;
+MarkerClusterer.prototype['repaint'] =
+ MarkerClusterer.prototype.repaint;
+MarkerClusterer.prototype['setCalculator'] =
+ MarkerClusterer.prototype.setCalculator;
+MarkerClusterer.prototype['setGridSize'] =
+ MarkerClusterer.prototype.setGridSize;
+MarkerClusterer.prototype['setMaxZoom'] =
+ MarkerClusterer.prototype.setMaxZoom;
+MarkerClusterer.prototype['onAdd'] = MarkerClusterer.prototype.onAdd;
+MarkerClusterer.prototype['draw'] = MarkerClusterer.prototype.draw;
+
+Cluster.prototype['getCenter'] = Cluster.prototype.getCenter;
+Cluster.prototype['getSize'] = Cluster.prototype.getSize;
+Cluster.prototype['getMarkers'] = Cluster.prototype.getMarkers;
+
+ClusterIcon.prototype['onAdd'] = ClusterIcon.prototype.onAdd;
+ClusterIcon.prototype['draw'] = ClusterIcon.prototype.draw;
+ClusterIcon.prototype['onRemove'] = ClusterIcon.prototype.onRemove;
+
+Object.keys = Object.keys || function(o) {
+ var result = [];
+ for(var name in o) {
+ if (o.hasOwnProperty(name))
+ result.push(name);
+ }
+ return result;
+};
|
rtucker/rgeoutages
|
98070d0cb23776b1d7c3b3215cbf8a1b7867287e
|
Google Maps API v3 support
|
diff --git a/generate_map.py b/generate_map.py
index 3db9c7e..9edf79d 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,484 +1,469 @@
#!/usr/bin/python
# vim: set fileencoding=utf-8 :
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
import scrape_rge
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache2)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache2
(town text, location text, streetname text, latitude real,
longitude real, formattedaddress text, locationtype text,
lastcheck integer, viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location, street):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
if location:
location = location.lower().strip()
else:
location = town
street = street.lower().strip()
if street.endswith(' la'):
street += 'ne'
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache2 where town=? and location=? and streetname=? order by lastcheck desc limit 1', (town, location, street))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(street + ", " + location + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache2 (town, location, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?,?)', (town, location, street, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = u"""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="900"/>
<title>(%i) Rochester, New York Power Outage Map</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
-<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
-<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
+<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3&key=%s&sensor=false"></script>
+<script type="text/javascript" src="markerclusterer.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
- var map = null;
- var mgr = null;
-
- function createMarker(point, text, color) {
- var baseIcon = new GIcon(G_DEFAULT_ICON);
- baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
- baseIcon.iconSize = new GSize(20, 34);
- baseIcon.shadowSize = new GSize(37, 34);
- baseIcon.iconAnchor = new GPoint(9, 34);
- baseIcon.infoWindowAnchor = new GPoint(9, 2);
-
- var ouricon = new GIcon(baseIcon);
- ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
-
- // Set up our GMarkerOptions object
- markerOptions = { icon:ouricon };
- var marker = new GMarker(point, markerOptions);
+ function createMarker(map, infowindow, position, title, text, color) {
+ var marker = new google.maps.Marker({
+ title: title,
+ position: position,
+ icon: "//www.google.com/mapfiles/marker_" + color + ".png"
+ });
- GEvent.addListener(marker, "click", function() {
- marker.openInfoWindowHtml(text);
+ google.maps.event.addListener(marker, "click", function() {
+ infowindow.content = text;
+ infowindow.open(map, marker);
});
+
return marker;
}
""" % (len(markers), apikey)
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 30:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 8:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 29:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
- if len(markers) > 300:
- out += u"""
- function setupMarkers() {
- var batch = [];
- %s
- mgr.addMarkers(batch, 12);
- var batch = [];
- %s
- mgr.addMarkers(batch, 1, 12);
- mgr.refresh();
- }
- """ % ('\n'.join(markers), '\n'.join(centers))
- zoom = min(zoom, 11)
- else:
- out += u"""
- function setupMarkers() {
- var batch = [];
- %s
- mgr.addMarkers(batch, 1);
- mgr.refresh();
- }
- """ % '\n'.join(markers)
+ out += u"""
+ function setupMarkers(map, infowindow) {
+ var batch = [];
+ %s
+ return batch;
+ }
+ """ % '\n'.join(markers)
out += u"""
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += u"""
function initialize() {
- if (GBrowserIsCompatible()) {
- map = new GMap2(document.getElementById("map_canvas"));
- map.setCenter(new GLatLng(%.4f, %.4f), %i);
- map.setUIToDefault();
- mgr = new MarkerManager(map);
- window.setTimeout(setupMarkers, 0);
-
- // Monitor the window resize event and let the map know when it occurs
- if (window.attachEvent) {
- window.attachEvent("onresize", function() {this.map.onResize()} );
- } else {
- window.addEventListener("resize", function() {this.map.onResize()} , false);
- }
- }
- } """ % (centerLat, centerLng, zoom)
+ var map = new google.maps.Map(
+ document.getElementById("map_canvas"), {
+ center: new google.maps.LatLng(%.4f, %.4f),
+ zoom: %i,
+ mapTypeId: google.maps.MapTypeId.TERRAIN
+ });
+
+ var infowindow = new google.maps.InfoWindow({
+ content: "lorem ipsum"
+ });
+
+ var markerCluster = new MarkerClusterer(map, setupMarkers(map, infowindow));
+ };
+ google.maps.event.addDomListener(window, 'load', initialize);
+
+ """ % (centerLat, centerLng, zoom)
out += u"""
</script>
</head>
"""
return out
-def produceMarker(lat, long, text, firstreport=-1, streetinfo={}):
+def produceMarker(lat, lng, text, firstreport=-1, streetinfo={}):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
color = 'grey'
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
streetinfo['FirstReported'] = nicetime
# colors available:
# black, brown, green, purple, yellow, grey, orange, white
if age < 15*60:
color = 'white'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
color = 'purple'
elif age < 65*60:
color = 'orange'
elif age < 115*60:
color = 'brown'
else:
color = 'black'
- text = '<strong>' + text + '</strong><br />' + '<br />'.join('%s: %s' % (key, value) for key, value in streetinfo.items())
- return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "%s"));' % (lat, long, text, color)
+ longtext = '<strong>' + text + '</strong><br />' + '<br />'.join('%s: %s' % (key, value) for key, value in streetinfo.items())
+ return 'batch.push(new createMarker(map, infowindow, new google.maps.LatLng(%f, %f), "%s", "%s", "%s"));' % (lat, lng, text, longtext, color)
def produceMapBody(body):
- return u""" <body onload="initialize()" onunload="GUnload()">
+ return u""" <body>
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
newjsondict = {}
# fetch the outages
outagedata = scrape_rge.crawl_outages()
for county, countydata in outagedata.items():
newjsondict[county] = {}
towns = countydata['Towns']
for town, towndata in towns.items():
newjsondict[county][town] = {}
locations = towndata['Locations']
count = 0
for location, locationdata in locations.items():
streets = locationdata['Streets']
newjsondict[county][town][location] = {}
for street, streetdata in streets.items():
newjsondict[county][town][location][street] = {}
for key, value in streetdata.items():
newjsondict[county][town][location][street][key] = value
try:
streetinfo = geocode(db, town, location, street)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
if streetinfo['locationtype'] == 'APPROXIMATE':
streetinfo['formattedaddress'] = '%s? (%s)' % (street, streetinfo['formattedaddress'])
newjsondict[county][town][location][street]['geo'] = streetinfo
newjsondict[county][town][location][street]['firstreport'] = firstreport
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport, streetdata))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (street, town, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
citycenter = geocode(db, town, '', '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress'] + ' (%i street%s)' % (count, s)))
localestring = '<strong>%s</strong>: %i street%s' % (town, count, s)
for key, value in towndata.items():
if type(value) is not dict:
localestring += ', %s: %s' % (key, value)
localestring += ' (%.2f%% affected)' % (float(towndata['CustomersWithoutPower']) / float(towndata['TotalCustomers']) * 100.0)
localelist.append(localestring)
# Save json history file
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
# Save json dump file
newjsonfd = open('data.new.json','w')
json.dump(newjsondict, newjsonfd)
newjsonfd.close()
os.rename('data.new.json', 'data.json')
- if len(markerlist) > 300:
- s = 's -- zoom for more detail'
- elif len(markerlist) == 1:
+ # XXX: DEBUG CODE
+ if False:
+ c = db.cursor()
+ c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache2 where town=? order by lastcheck desc', ("rochester",))
+
+ for i, r in enumerate(c.fetchall()):
+ markerlist.append(produceMarker(r[0], r[1], r[2], i, {'debug': "num %d" % i}))
+ # XXX: END DEBUG
+
+ if len(markerlist) == 1:
s = ''
else:
s = 's'
+
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist).encode("utf-8"))
bodytext = u"""
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Rochester-area Power Outage Map</b> as of %s (%i street%s)</b></p>
<p style="font-size:small;"><a href="javascript:unhide('faqbox');">More information about this map</a> |
<a href="javascript:unhide('chartbox');">Outage graph</a> |
<a href="data.json">JSON</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p>This map plots the approximate locations of power outages in Rochester, New York, and is updated every ten minutes. The source data for this map is published by <A HREF="http://www.rge.com/Outages/outageinformation.html">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="https://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
<li><b>This page may be out of date.</b> This page does not get regenerated if there are no outages. (Pure laziness on my part.) If in doubt, check the as-of time.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<hr>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<p style="font-size:xx-small;"><a href="https://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(http://munin.sodtech.net/hoopycat.com/framboise/rgeoutages-day.png); width:495px; height:271px;"></div>
</div>
""" % (time.asctime(), len(markerlist), s, '<br/>'.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
794e262a8a63878364701b28d534e2e73af1a1ed
|
Google Maps v3: change geocode endpoint
|
diff --git a/generate_map.py b/generate_map.py
index be3d86a..3db9c7e 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,484 +1,484 @@
#!/usr/bin/python
# vim: set fileencoding=utf-8 :
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
import scrape_rge
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache2)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache2
(town text, location text, streetname text, latitude real,
longitude real, formattedaddress text, locationtype text,
lastcheck integer, viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
- response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
+ response = urllib2.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location, street):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
if location:
location = location.lower().strip()
else:
location = town
street = street.lower().strip()
if street.endswith(' la'):
street += 'ne'
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache2 where town=? and location=? and streetname=? order by lastcheck desc limit 1', (town, location, street))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(street + ", " + location + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache2 (town, location, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?,?)', (town, location, street, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = u"""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="900"/>
<title>(%i) Rochester, New York Power Outage Map</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % (len(markers), apikey)
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 30:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 8:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 29:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += u"""
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += u"""
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += u"""
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += u"""
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += u"""
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1, streetinfo={}):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
color = 'grey'
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
streetinfo['FirstReported'] = nicetime
# colors available:
# black, brown, green, purple, yellow, grey, orange, white
if age < 15*60:
color = 'white'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
color = 'purple'
elif age < 65*60:
color = 'orange'
elif age < 115*60:
color = 'brown'
else:
color = 'black'
text = '<strong>' + text + '</strong><br />' + '<br />'.join('%s: %s' % (key, value) for key, value in streetinfo.items())
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "%s"));' % (lat, long, text, color)
def produceMapBody(body):
return u""" <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
newjsondict = {}
# fetch the outages
outagedata = scrape_rge.crawl_outages()
for county, countydata in outagedata.items():
newjsondict[county] = {}
towns = countydata['Towns']
for town, towndata in towns.items():
newjsondict[county][town] = {}
locations = towndata['Locations']
count = 0
for location, locationdata in locations.items():
streets = locationdata['Streets']
newjsondict[county][town][location] = {}
for street, streetdata in streets.items():
newjsondict[county][town][location][street] = {}
for key, value in streetdata.items():
newjsondict[county][town][location][street][key] = value
try:
streetinfo = geocode(db, town, location, street)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
if streetinfo['locationtype'] == 'APPROXIMATE':
streetinfo['formattedaddress'] = '%s? (%s)' % (street, streetinfo['formattedaddress'])
newjsondict[county][town][location][street]['geo'] = streetinfo
newjsondict[county][town][location][street]['firstreport'] = firstreport
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport, streetdata))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (street, town, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
citycenter = geocode(db, town, '', '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress'] + ' (%i street%s)' % (count, s)))
localestring = '<strong>%s</strong>: %i street%s' % (town, count, s)
for key, value in towndata.items():
if type(value) is not dict:
localestring += ', %s: %s' % (key, value)
localestring += ' (%.2f%% affected)' % (float(towndata['CustomersWithoutPower']) / float(towndata['TotalCustomers']) * 100.0)
localelist.append(localestring)
# Save json history file
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
# Save json dump file
newjsonfd = open('data.new.json','w')
json.dump(newjsondict, newjsonfd)
newjsonfd.close()
os.rename('data.new.json', 'data.json')
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) == 1:
s = ''
else:
s = 's'
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist).encode("utf-8"))
bodytext = u"""
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Rochester-area Power Outage Map</b> as of %s (%i street%s)</b></p>
<p style="font-size:small;"><a href="javascript:unhide('faqbox');">More information about this map</a> |
<a href="javascript:unhide('chartbox');">Outage graph</a> |
<a href="data.json">JSON</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p>This map plots the approximate locations of power outages in Rochester, New York, and is updated every ten minutes. The source data for this map is published by <A HREF="http://www.rge.com/Outages/outageinformation.html">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="https://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
<li><b>This page may be out of date.</b> This page does not get regenerated if there are no outages. (Pure laziness on my part.) If in doubt, check the as-of time.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<hr>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<p style="font-size:xx-small;"><a href="https://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(http://munin.sodtech.net/hoopycat.com/framboise/rgeoutages-day.png); width:495px; height:271px;"></div>
</div>
""" % (time.asctime(), len(markerlist), s, '<br/>'.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
5b3d5752d40ebdafd21d71e8e029f42f6176542f
|
overload mode fixes
|
diff --git a/generate_map.py b/generate_map.py
index b766609..be3d86a 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,481 +1,484 @@
#!/usr/bin/python
# vim: set fileencoding=utf-8 :
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
import scrape_rge
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache2)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache2
(town text, location text, streetname text, latitude real,
longitude real, formattedaddress text, locationtype text,
lastcheck integer, viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location, street):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
- location = location.lower().strip()
+ if location:
+ location = location.lower().strip()
+ else:
+ location = town
street = street.lower().strip()
if street.endswith(' la'):
street += 'ne'
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache2 where town=? and location=? and streetname=? order by lastcheck desc limit 1', (town, location, street))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(street + ", " + location + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache2 (town, location, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?,?)', (town, location, street, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = u"""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="900"/>
<title>(%i) Rochester, New York Power Outage Map</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % (len(markers), apikey)
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 30:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 8:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 29:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += u"""
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += u"""
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += u"""
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += u"""
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += u"""
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1, streetinfo={}):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
color = 'grey'
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
streetinfo['FirstReported'] = nicetime
# colors available:
# black, brown, green, purple, yellow, grey, orange, white
if age < 15*60:
color = 'white'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
color = 'purple'
elif age < 65*60:
color = 'orange'
elif age < 115*60:
color = 'brown'
else:
color = 'black'
text = '<strong>' + text + '</strong><br />' + '<br />'.join('%s: %s' % (key, value) for key, value in streetinfo.items())
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "%s"));' % (lat, long, text, color)
def produceMapBody(body):
return u""" <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
newjsondict = {}
# fetch the outages
outagedata = scrape_rge.crawl_outages()
for county, countydata in outagedata.items():
newjsondict[county] = {}
towns = countydata['Towns']
for town, towndata in towns.items():
newjsondict[county][town] = {}
locations = towndata['Locations']
count = 0
- citycenter = geocode(db, town, '', '')
- citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
-
for location, locationdata in locations.items():
streets = locationdata['Streets']
newjsondict[county][town][location] = {}
for street, streetdata in streets.items():
newjsondict[county][town][location][street] = {}
for key, value in streetdata.items():
newjsondict[county][town][location][street][key] = value
try:
streetinfo = geocode(db, town, location, street)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
if streetinfo['locationtype'] == 'APPROXIMATE':
streetinfo['formattedaddress'] = '%s? (%s)' % (street, streetinfo['formattedaddress'])
newjsondict[county][town][location][street]['geo'] = streetinfo
newjsondict[county][town][location][street]['firstreport'] = firstreport
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport, streetdata))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (street, town, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
+ citycenter = geocode(db, town, '', '')
+ citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress'] + ' (%i street%s)' % (count, s)))
+
localestring = '<strong>%s</strong>: %i street%s' % (town, count, s)
for key, value in towndata.items():
if type(value) is not dict:
localestring += ', %s: %s' % (key, value)
localestring += ' (%.2f%% affected)' % (float(towndata['CustomersWithoutPower']) / float(towndata['TotalCustomers']) * 100.0)
localelist.append(localestring)
# Save json history file
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
# Save json dump file
newjsonfd = open('data.new.json','w')
json.dump(newjsondict, newjsonfd)
newjsonfd.close()
os.rename('data.new.json', 'data.json')
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) == 1:
s = ''
else:
s = 's'
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist).encode("utf-8"))
bodytext = u"""
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Rochester-area Power Outage Map</b> as of %s (%i street%s)</b></p>
<p style="font-size:small;"><a href="javascript:unhide('faqbox');">More information about this map</a> |
<a href="javascript:unhide('chartbox');">Outage graph</a> |
<a href="data.json">JSON</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p>This map plots the approximate locations of power outages in Rochester, New York, and is updated every ten minutes. The source data for this map is published by <A HREF="http://www.rge.com/Outages/outageinformation.html">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="https://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
<li><b>This page may be out of date.</b> This page does not get regenerated if there are no outages. (Pure laziness on my part.) If in doubt, check the as-of time.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<hr>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<p style="font-size:xx-small;"><a href="https://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(http://munin.sodtech.net/hoopycat.com/framboise/rgeoutages-day.png); width:495px; height:271px;"></div>
</div>
""" % (time.asctime(), len(markerlist), s, '<br/>'.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
7fbbc4bc3d3d096fba6029694db36f8ed14021ff
|
munin: fix path to json_xs
|
diff --git a/rgeoutages_munin.sh b/rgeoutages_munin.sh
index b25b4f2..849c229 100755
--- a/rgeoutages_munin.sh
+++ b/rgeoutages_munin.sh
@@ -1,30 +1,30 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages
if [ "$1" = "config" ]; then
cat <<EOM
graph_title RG&E Power Outage Summary
graph_args --base 1000 -l 0
graph_vlabel outages
graph_category Climate
customers.draw AREA
customers.label customers without power
outages.draw LINE
outages.label streets affected
EOM
elif [ "$1" = "autoconf" ]; then
if [ -f $BASEDIR/fetch_outages.sh ]; then
echo "yes"
else
echo "no"
fi
else
- customercount=`json_xs -t yaml < $BASEDIR/data.json | grep CustomersWithoutPower | awk '{ sum += $2 }; END { print sum }'`
+ customercount=`/usr/local/bin/json_xs -t yaml < $BASEDIR/data.json | grep CustomersWithoutPower | awk '{ sum += $2 }; END { print sum }'`
outagecount=`/usr/local/bin/json_xs < $BASEDIR/history.json | grep -c " "`
echo "customers.value $customercount"
echo "outages.value $outagecount"
fi
|
rtucker/rgeoutages
|
31008af3b1b5c45d97b3ec70a50cf2c9c2ba1fc3
|
munin: graph total customers affected
|
diff --git a/rgeoutages_munin.sh b/rgeoutages_munin.sh
index 2b8f68d..b25b4f2 100755
--- a/rgeoutages_munin.sh
+++ b/rgeoutages_munin.sh
@@ -1,26 +1,30 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages
if [ "$1" = "config" ]; then
cat <<EOM
graph_title RG&E Power Outage Summary
graph_args --base 1000 -l 0
graph_vlabel outages
graph_category Climate
-outages.draw AREA
-outages.label outages
+customers.draw AREA
+customers.label customers without power
+outages.draw LINE
+outages.label streets affected
EOM
elif [ "$1" = "autoconf" ]; then
if [ -f $BASEDIR/fetch_outages.sh ]; then
echo "yes"
else
echo "no"
fi
else
+ customercount=`json_xs -t yaml < $BASEDIR/data.json | grep CustomersWithoutPower | awk '{ sum += $2 }; END { print sum }'`
outagecount=`/usr/local/bin/json_xs < $BASEDIR/history.json | grep -c " "`
+ echo "customers.value $customercount"
echo "outages.value $outagecount"
fi
|
rtucker/rgeoutages
|
e19bab973a9a1fc436b1063304c5e7ecba23043f
|
hardcode path to json_xs
|
diff --git a/rgeoutages_munin.sh b/rgeoutages_munin.sh
index 6a2688c..2b8f68d 100755
--- a/rgeoutages_munin.sh
+++ b/rgeoutages_munin.sh
@@ -1,26 +1,26 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages
if [ "$1" = "config" ]; then
cat <<EOM
graph_title RG&E Power Outage Summary
graph_args --base 1000 -l 0
graph_vlabel outages
graph_category Climate
outages.draw AREA
outages.label outages
EOM
elif [ "$1" = "autoconf" ]; then
if [ -f $BASEDIR/fetch_outages.sh ]; then
echo "yes"
else
echo "no"
fi
else
- outagecount=`json_xs < $BASEDIR/history.json | grep -c " "`
+ outagecount=`/usr/local/bin/json_xs < $BASEDIR/history.json | grep -c " "`
echo "outages.value $outagecount"
fi
|
rtucker/rgeoutages
|
f764ea934f3ab615d5c4a8bd1a4fa55153537d23
|
add data.json output; write map even if there are no outages
|
diff --git a/.gitignore b/.gitignore
index 4b21cfa..0cfe77f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,7 +1,7 @@
index.html
outages_*
secrets.py
*.pyc
*.sqlite3
outagechart.png
-history.json
+*.json
diff --git a/generate_map.py b/generate_map.py
index 6a35888..2844db1 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,456 +1,470 @@
#!/usr/bin/python
# vim: set fileencoding=utf-8 :
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
import scrape_rge
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = u"""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>(%i) Rochester, New York Power Outage Map</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % (len(markers), apikey)
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 30:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 8:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 29:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += u"""
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += u"""
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += u"""
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += u"""
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += u"""
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1, streetinfo={}):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
color = 'grey'
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
streetinfo['FirstReported'] = nicetime
# colors available:
# black, brown, green, purple, yellow, grey, orange, white
if age < 15*60:
color = 'white'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
color = 'purple'
elif age < 65*60:
color = 'orange'
elif age < 115*60:
color = 'brown'
else:
color = 'black'
text = '<strong>' + text + '</strong><br />' + '<br />'.join('%s: %s' % (key, value) for key, value in streetinfo.items())
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "%s"));' % (lat, long, text, color)
def produceMapBody(body):
return u""" <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
+ newjsondict = {}
# fetch the outages
outagedata = scrape_rge.crawl_outages()
for county, countydata in outagedata.items():
+ newjsondict[county] = {}
towns = countydata['Towns']
for town, towndata in towns.items():
+ newjsondict[county][town] = {}
streets = towndata['Streets']
count = 0
citycenter = geocode(db, town, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for street, streetdata in streets.items():
+ newjsondict[county][town][street] = {}
+ for key, value in streetdata.items():
+ newjsondict[county][town][street][key] = value
try:
streetinfo = geocode(db, town, street)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
+ newjsondict[county][town][street]['geo'] = streetinfo
+ newjsondict[county][town][street]['firstreport'] = firstreport
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport, streetdata))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (street, town, e.__str__()))
-
if count > 1:
s = 's'
else:
s = ''
localestring = '<strong>%s</strong>: %i street%s' % (town, count, s)
for key, value in towndata.items():
if type(value) is not dict:
localestring += ', %s: %s' % (key, value)
localelist.append(localestring)
+ # Save json history file
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
- if len(markerlist) > 0:
- if len(markerlist) > 300:
- s = 's -- zoom for more detail'
- elif len(markerlist) > 1:
- s = 's'
- else:
- s = ''
- sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist).encode("utf-8"))
-
- bodytext = u"""
- <div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
- <div id="closebutton" style="top:2px; right:2px; position:absolute">
- <a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
- </div>
- <p><b>Rochester-area Power Outage Map</b> as of %s (%i street%s)</b></p>
- <p style="font-size:small;"><a href="javascript:unhide('faqbox');">More information about this map</a> |
- <a href="javascript:unhide('chartbox');">Outage graph</a></p>
- <p style="font-size:xx-small;">%s</p>
- </div>
+ # Save json dump file
+ newjsonfd = open('data.new.json','w')
+ json.dump(newjsondict, newjsonfd)
+ newjsonfd.close()
+ os.rename('data.new.json', 'data.json')
- <div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
- <div id="closebutton" style="top:2px; right:2px; position:absolute">
- <a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
- </div>
- <p>This map plots the approximate locations of power outages in Rochester, New York, and is updated every ten minutes. The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="https://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
- <p>Some important tips to keep in mind...</p>
- <ul>
- <li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
- <li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
- <li><b>This page may be out of date.</b> This page does not get regenerated if there are no outages. (Pure laziness on my part.) If in doubt, check the as-of time.</li>
- </ul>
- <p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
- <hr>
- <p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
- <p style="font-size:xx-small;"><a href="https://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
- </div>
+ if len(markerlist) > 300:
+ s = 's -- zoom for more detail'
+ elif len(markerlist) == 1:
+ s = ''
+ else:
+ s = 's'
+ sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist).encode("utf-8"))
- <div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
- <div id="closebutton" style="top:2px; right:2px; position:absolute">
- <a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
- </div>
- <div id="graphimage" style="background:url(http://munin.sodtech.net/hoopycat.com/framboise/rgeoutages-day.png); width:495px; height:271px;"></div>
+ bodytext = u"""
+ <div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
+ <div id="closebutton" style="top:2px; right:2px; position:absolute">
+ <a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
+ </div>
+ <p><b>Rochester-area Power Outage Map</b> as of %s (%i outage%s)</b></p>
+ <p style="font-size:small;"><a href="javascript:unhide('faqbox');">More information about this map</a> |
+ <a href="javascript:unhide('chartbox');">Outage graph</a> |
+ <a href="data.json">JSON</a></p>
+ <p style="font-size:xx-small;">%s</p>
+ </div>
+
+ <div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
+ <div id="closebutton" style="top:2px; right:2px; position:absolute">
+ <a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
+ </div>
+ <p>This map plots the approximate locations of power outages in Rochester, New York, and is updated every ten minutes. The source data for this map is published by <A HREF="http://www.rge.com/Outages/outageinformation.html">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="https://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
+ <p>Some important tips to keep in mind...</p>
+ <ul>
+ <li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
+ <li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
+ <li><b>This page may be out of date.</b> This page does not get regenerated if there are no outages. (Pure laziness on my part.) If in doubt, check the as-of time.</li>
+ </ul>
+ <p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
+ <hr>
+ <p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
+ <p style="font-size:xx-small;"><a href="https://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
+ </div>
+
+ <div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
+ <div id="closebutton" style="top:2px; right:2px; position:absolute">
+ <a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
+ <div id="graphimage" style="background:url(http://munin.sodtech.net/hoopycat.com/framboise/rgeoutages-day.png); width:495px; height:271px;"></div>
+ </div>
- """ % (time.asctime(), len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
+ """ % (time.asctime(), len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
- sys.stdout.write(produceMapBody(bodytext))
+ sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
16a721989acf3611cf846bfc7723a9b1de827bed
|
skip non-local links in crawling (usually means no outages)
|
diff --git a/scrape_rge.py b/scrape_rge.py
index 44dbc02..68ded36 100644
--- a/scrape_rge.py
+++ b/scrape_rge.py
@@ -1,109 +1,113 @@
#!/usr/bin/python
# Scrapes RG&E outage information.
# Requires:
# python-pycurl
# python-beautifulsoup
import os
import pycurl
import StringIO
from BeautifulSoup import BeautifulSoup
BASE_URL="http://www3.rge.com/OutageReports/"
START_URL="RGE.html"
try:
GIT_VERSION = open('.git/refs/heads/master','r').read().strip()
GIT_MODTIME = os.stat('.git/refs/heads/master').st_mtime
except IOError:
GIT_MODTIME = GIT_VERSION = "dev"
USERAGENT="rgeoutages/%s (http://hoopycat.com/rgeoutages/; version %s)" % (GIT_MODTIME, GIT_VERSION)
def get_url(url):
c = pycurl.Curl()
c.setopt(pycurl.URL, str(url))
c.setopt(pycurl.USERAGENT, USERAGENT)
b = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.perform()
b.seek(0)
return b
def scrape_table(table):
data = {}
headings = []
for row in table('tr'):
if row.th:
if len(row('th')) > 1 and str(row.th.string) != str(' '):
headings = [cell.renderContents() for cell in row('th')]
elif row.td:
contents = [cell.renderContents() for cell in row('td')]
href = None
if row('td')[0].a:
for attr in row('td')[0].a.attrs:
if attr[0] == 'href':
href = attr[1]
contents[0] = row('td')[0].a.contents[0]
if href:
data[href] = contents
elif not contents[0].startswith('&'):
data[contents[0]] = contents[1:]
return (headings, data)
def get_soup(url):
content = get_url(url).readlines()
return BeautifulSoup(''.join(content))
def crawl_outages(base_url=BASE_URL, start_url=START_URL):
outages = {}
# Get bunch of counties
countysoup = get_soup(base_url + start_url)
countyheadings, countydata = scrape_table(countysoup.table)
# From here, we need to get a bunch of towns...
for countyfile, countyrow in countydata.items():
+ if countyfile.startswith('http'):
+ # It isn't our normal relative URL; ignore it
+ continue
+
townsoup = get_soup(base_url + countyfile)
townheadings, towndata = scrape_table(townsoup.table)
# And then a bunch of streets...
countydict = {}
for townfile, townrow in towndata.items():
if str(townfile) == str(start_url):
continue
towndict = {}
streetsoup = get_soup(base_url + townfile)
streetheadings, streetdata = scrape_table(streetsoup.table)
for streetname, streetrow in streetdata.items():
if str(streetname) == str(countyfile):
continue
if len(streetrow) == 2:
streetrow.append('Unknown')
towndict[streetname] = {
'TotalCustomers': streetrow[0],
'CustomersWithoutPower': streetrow[1],
'EstimatedRestoration': streetrow[2],
}
countydict[townrow[0]] = {
'TotalCustomers': townrow[1],
'CustomersWithoutPower': townrow[2],
'Streets': towndict,
}
outages[countyrow[0]] = {
'TotalCustomers': countyrow[1],
'CustomersWithoutPower': countyrow[2],
'Towns': countydict,
}
return outages
if __name__ == '__main__':
structure = crawl_outages(BASE_URL, START_URL)
print `structure`
|
rtucker/rgeoutages
|
01ca2cd136b4c917c2a99083ac0ea685f6915b7d
|
fix accidental deletion...
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
index bf0c0ff..47dea70 100755
--- a/fetch_outages.sh
+++ b/fetch_outages.sh
@@ -1,24 +1,24 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages/
GENERATOR=$BASEDIR/generate_map.py
HTMLFILE=$BASEDIR/index.html
export TZ=America/New_York
# Test for sanity
[ -d "$BASEDIR" ] || (echo "Base directory missing: $BASEDIR"; exit 1)
[ -x "$GENERATOR" ] || (echo "Generator script not executable: $GENERATOR"; exit 1)
# All together now
+cd $BASEDIR
TEMPFILE=`tempfile`
-
$GENERATOR > $TEMPFILE
if [ -n "`cat $TEMPFILE`" ]; then
cp $TEMPFILE $HTMLFILE
else
echo "$TEMPFILE was empty, utoh"
fi
rm $TEMPFILE
|
rtucker/rgeoutages
|
93b11d9a301b9e1cf3c61f9be2302ffcf48ff5d1
|
fix munin plugin for outage charting
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
index b1da252..bf0c0ff 100755
--- a/fetch_outages.sh
+++ b/fetch_outages.sh
@@ -1,23 +1,24 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages/
GENERATOR=$BASEDIR/generate_map.py
HTMLFILE=$BASEDIR/index.html
export TZ=America/New_York
# Test for sanity
[ -d "$BASEDIR" ] || (echo "Base directory missing: $BASEDIR"; exit 1)
[ -x "$GENERATOR" ] || (echo "Generator script not executable: $GENERATOR"; exit 1)
# All together now
-cd $BASEDIR
TEMPFILE=`tempfile`
+
$GENERATOR > $TEMPFILE
if [ -n "`cat $TEMPFILE`" ]; then
cp $TEMPFILE $HTMLFILE
else
echo "$TEMPFILE was empty, utoh"
fi
rm $TEMPFILE
+
diff --git a/rgeoutages_munin.sh b/rgeoutages_munin.sh
index 9274bb8..6a2688c 100755
--- a/rgeoutages_munin.sh
+++ b/rgeoutages_munin.sh
@@ -1,26 +1,26 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages
if [ "$1" = "config" ]; then
cat <<EOM
graph_title RG&E Power Outage Summary
graph_args --base 1000 -l 0
graph_vlabel outages
graph_category Climate
outages.draw AREA
outages.label outages
EOM
elif [ "$1" = "autoconf" ]; then
if [ -f $BASEDIR/fetch_outages.sh ]; then
echo "yes"
else
echo "no"
fi
else
- outagecount=`cat $BASEDIR/outages_*.txt | wc -l`
+ outagecount=`json_xs < $BASEDIR/history.json | grep -c " "`
echo "outages.value $outagecount"
fi
|
rtucker/rgeoutages
|
4906eac65011885dc566552038c2749941d64c93
|
fix current working directory
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
index bf0c0ff..b1da252 100755
--- a/fetch_outages.sh
+++ b/fetch_outages.sh
@@ -1,24 +1,23 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages/
GENERATOR=$BASEDIR/generate_map.py
HTMLFILE=$BASEDIR/index.html
export TZ=America/New_York
# Test for sanity
[ -d "$BASEDIR" ] || (echo "Base directory missing: $BASEDIR"; exit 1)
[ -x "$GENERATOR" ] || (echo "Generator script not executable: $GENERATOR"; exit 1)
# All together now
+cd $BASEDIR
TEMPFILE=`tempfile`
-
$GENERATOR > $TEMPFILE
if [ -n "`cat $TEMPFILE`" ]; then
cp $TEMPFILE $HTMLFILE
else
echo "$TEMPFILE was empty, utoh"
fi
rm $TEMPFILE
-
|
rtucker/rgeoutages
|
e478481827acc064d70be3ea7f325f666a7546c9
|
more compat changes
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
index 7bb4974..bf0c0ff 100755
--- a/fetch_outages.sh
+++ b/fetch_outages.sh
@@ -1,27 +1,24 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages/
GENERATOR=$BASEDIR/generate_map.py
HTMLFILE=$BASEDIR/index.html
export TZ=America/New_York
# Test for sanity
[ -d "$BASEDIR" ] || (echo "Base directory missing: $BASEDIR"; exit 1)
[ -x "$GENERATOR" ] || (echo "Generator script not executable: $GENERATOR"; exit 1)
# All together now
TEMPFILE=`tempfile`
$GENERATOR > $TEMPFILE
if [ -n "`cat $TEMPFILE`" ]; then
cp $TEMPFILE $HTMLFILE
else
echo "$TEMPFILE was empty, utoh"
fi
rm $TEMPFILE
-# Fetch a munin chart
-wget -q -O outagechart.png http://hennepin.hoopycat.com/munin/hoopycat.com/framboise/rgeoutages-day.png
-
diff --git a/generate_map.py b/generate_map.py
index 1ad04de..6a35888 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,452 +1,456 @@
#!/usr/bin/python
# vim: set fileencoding=utf-8 :
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
import scrape_rge
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = u"""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>(%i) Rochester, New York Power Outage Map</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % (len(markers), apikey)
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 30:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 8:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 29:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += u"""
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += u"""
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += u"""
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += u"""
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += u"""
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1, streetinfo={}):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
color = 'grey'
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
- streetinfo['First Reported'] = nicetime
+ streetinfo['FirstReported'] = nicetime
# colors available:
# black, brown, green, purple, yellow, grey, orange, white
if age < 15*60:
color = 'white'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
color = 'purple'
elif age < 65*60:
color = 'orange'
elif age < 115*60:
color = 'brown'
else:
color = 'black'
text = '<strong>' + text + '</strong><br />' + '<br />'.join('%s: %s' % (key, value) for key, value in streetinfo.items())
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "%s"));' % (lat, long, text, color)
def produceMapBody(body):
return u""" <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
# fetch the outages
outagedata = scrape_rge.crawl_outages()
for county, countydata in outagedata.items():
towns = countydata['Towns']
for town, towndata in towns.items():
streets = towndata['Streets']
count = 0
citycenter = geocode(db, town, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for street, streetdata in streets.items():
try:
streetinfo = geocode(db, town, street)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport, streetdata))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (street, town, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
- localelist.append('%s: %i street%s' % (town, count, s))
+ localestring = '<strong>%s</strong>: %i street%s' % (town, count, s)
+ for key, value in towndata.items():
+ if type(value) is not dict:
+ localestring += ', %s: %s' % (key, value)
+ localelist.append(localestring)
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist).encode("utf-8"))
bodytext = u"""
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Rochester-area Power Outage Map</b> as of %s (%i street%s)</b></p>
<p style="font-size:small;"><a href="javascript:unhide('faqbox');">More information about this map</a> |
<a href="javascript:unhide('chartbox');">Outage graph</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p>This map plots the approximate locations of power outages in Rochester, New York, and is updated every ten minutes. The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="https://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
<li><b>This page may be out of date.</b> This page does not get regenerated if there are no outages. (Pure laziness on my part.) If in doubt, check the as-of time.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<hr>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<p style="font-size:xx-small;"><a href="https://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
- <div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
+ <div id="graphimage" style="background:url(http://munin.sodtech.net/hoopycat.com/framboise/rgeoutages-day.png); width:495px; height:271px;"></div>
</div>
- """ % ('N/A', len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
+ """ % (time.asctime(), len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
0a327c4ba753fa4d4980bc9fce7f1fc68390d976
|
Fix it to work with RG&E's new outage reporting site
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
index 17266a8..7bb4974 100755
--- a/fetch_outages.sh
+++ b/fetch_outages.sh
@@ -1,55 +1,27 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages/
GENERATOR=$BASEDIR/generate_map.py
HTMLFILE=$BASEDIR/index.html
export TZ=America/New_York
# Test for sanity
[ -d "$BASEDIR" ] || (echo "Base directory missing: $BASEDIR"; exit 1)
[ -x "$GENERATOR" ] || (echo "Generator script not executable: $GENERATOR"; exit 1)
-# Fetch location list
-TEMPFILE=`tempfile`
-wget -q -O $TEMPFILE http://ebiz1.rge.com/cusweb/outage/index.aspx
-
-LOCATIONS=`grep "<option value=\"14|" $TEMPFILE | cut -d'|' -f2 | cut -d'"' -f1 | sed "s/ /%20/g" | xargs`
-
-rm $TEMPFILE
-
-# Fetch street data
-cd $BASEDIR || (echo "Could not cd to $BASEDIR"; exit 1)
-rm outages_*.txt 2>/dev/null
-
-for i in $LOCATIONS
-do
- TEMPFILE=`tempfile`
- OUTFILE=outages_$i.txt
- wget -q -O $TEMPFILE "http://ebiz1.rge.com/cusweb/outage/roadoutages.aspx?town=$i"
- grep "wcHeader_Label3" $TEMPFILE \
- | cut -d'>' -f2 | cut -d'<' -f1 > $OUTFILE
- grep "<td nowrap=\"nowrap\">" $TEMPFILE \
- | cut -d">" -f2 | cut -d"<" -f1 >> $OUTFILE
- rm $TEMPFILE
- sleep 2
-done
-
# All together now
TEMPFILE=`tempfile`
-$GENERATOR $LOCATIONS > $TEMPFILE
+$GENERATOR > $TEMPFILE
if [ -n "`cat $TEMPFILE`" ]; then
cp $TEMPFILE $HTMLFILE
-elif [ -z "$LOCATIONS" ] ; then
- # there are no outages! do something cool.
- true
else
echo "$TEMPFILE was empty, utoh"
fi
rm $TEMPFILE
# Fetch a munin chart
wget -q -O outagechart.png http://hennepin.hoopycat.com/munin/hoopycat.com/framboise/rgeoutages-day.png
diff --git a/generate_map.py b/generate_map.py
index 4184688..1ad04de 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,450 +1,452 @@
#!/usr/bin/python
# vim: set fileencoding=utf-8 :
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
+import scrape_rge
+
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = u"""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>(%i) Rochester, New York Power Outage Map</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % (len(markers), apikey)
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 30:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 8:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 29:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += u"""
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += u"""
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += u"""
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += u"""
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += u"""
</script>
</head>
"""
return out
-def produceMarker(lat, long, text, firstreport=-1):
+def produceMarker(lat, long, text, firstreport=-1, streetinfo={}):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
+ color = 'grey'
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
+ streetinfo['First Reported'] = nicetime
# colors available:
# black, brown, green, purple, yellow, grey, orange, white
if age < 15*60:
color = 'white'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
color = 'purple'
elif age < 65*60:
color = 'orange'
elif age < 115*60:
color = 'brown'
else:
color = 'black'
- return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s<br>First reported: %s", "%s"));' % (lat, long, text, nicetime, color)
- else:
- return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "grey"));' % (lat, long, text)
+
+ text = '<strong>' + text + '</strong><br />' + '<br />'.join('%s: %s' % (key, value) for key, value in streetinfo.items())
+ return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "%s"));' % (lat, long, text, color)
def produceMapBody(body):
return u""" <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
- for i in sys.argv[1:]:
- if i in stoplist:
- continue
-
- fd = open('outages_%s.txt' % i)
- lastupdated = fd.readline()
- cleanname = i.replace('%20', ' ')
-
- count = 0
-
- citycenter = geocode(db, cleanname, '')
- citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
-
- for j in fd.readlines():
- try:
- streetinfo = geocode(db, cleanname, j)
- if streetinfo['formattedaddress'] in historydict.keys():
- firstreport = historydict[streetinfo['formattedaddress']]
- else:
- firstreport = time.time()
- markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport))
- pointlist.append(streetinfo)
- newhistorydict[streetinfo['formattedaddress']] = firstreport
- count += 1
- except Exception, e:
- sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
-
- if count > 1:
- s = 's'
- else:
- s = ''
-
- localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
+ # fetch the outages
+ outagedata = scrape_rge.crawl_outages()
+
+ for county, countydata in outagedata.items():
+ towns = countydata['Towns']
+ for town, towndata in towns.items():
+ streets = towndata['Streets']
+ count = 0
+ citycenter = geocode(db, town, '')
+ citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
+
+ for street, streetdata in streets.items():
+ try:
+ streetinfo = geocode(db, town, street)
+ if streetinfo['formattedaddress'] in historydict.keys():
+ firstreport = historydict[streetinfo['formattedaddress']]
+ else:
+ firstreport = time.time()
+ markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport, streetdata))
+ pointlist.append(streetinfo)
+ newhistorydict[streetinfo['formattedaddress']] = firstreport
+ count += 1
+ except Exception, e:
+ sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (street, town, e.__str__()))
+
+ if count > 1:
+ s = 's'
+ else:
+ s = ''
+
+ localelist.append('%s: %i street%s' % (town, count, s))
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist).encode("utf-8"))
bodytext = u"""
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Rochester-area Power Outage Map</b> as of %s (%i street%s)</b></p>
<p style="font-size:small;"><a href="javascript:unhide('faqbox');">More information about this map</a> |
<a href="javascript:unhide('chartbox');">Outage graph</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p>This map plots the approximate locations of power outages in Rochester, New York, and is updated every ten minutes. The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="https://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
<li><b>This page may be out of date.</b> This page does not get regenerated if there are no outages. (Pure laziness on my part.) If in doubt, check the as-of time.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<hr>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<p style="font-size:xx-small;"><a href="https://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
- """ % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
+ """ % ('N/A', len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
diff --git a/scrape_rge.py b/scrape_rge.py
new file mode 100644
index 0000000..44dbc02
--- /dev/null
+++ b/scrape_rge.py
@@ -0,0 +1,109 @@
+#!/usr/bin/python
+
+# Scrapes RG&E outage information.
+# Requires:
+# python-pycurl
+# python-beautifulsoup
+
+import os
+import pycurl
+import StringIO
+
+from BeautifulSoup import BeautifulSoup
+
+BASE_URL="http://www3.rge.com/OutageReports/"
+START_URL="RGE.html"
+
+try:
+ GIT_VERSION = open('.git/refs/heads/master','r').read().strip()
+ GIT_MODTIME = os.stat('.git/refs/heads/master').st_mtime
+except IOError:
+ GIT_MODTIME = GIT_VERSION = "dev"
+
+USERAGENT="rgeoutages/%s (http://hoopycat.com/rgeoutages/; version %s)" % (GIT_MODTIME, GIT_VERSION)
+
+def get_url(url):
+ c = pycurl.Curl()
+ c.setopt(pycurl.URL, str(url))
+ c.setopt(pycurl.USERAGENT, USERAGENT)
+ b = StringIO.StringIO()
+ c.setopt(pycurl.WRITEFUNCTION, b.write)
+ c.perform()
+ b.seek(0)
+ return b
+
+def scrape_table(table):
+ data = {}
+ headings = []
+
+ for row in table('tr'):
+ if row.th:
+ if len(row('th')) > 1 and str(row.th.string) != str(' '):
+ headings = [cell.renderContents() for cell in row('th')]
+ elif row.td:
+ contents = [cell.renderContents() for cell in row('td')]
+ href = None
+ if row('td')[0].a:
+ for attr in row('td')[0].a.attrs:
+ if attr[0] == 'href':
+ href = attr[1]
+ contents[0] = row('td')[0].a.contents[0]
+ if href:
+ data[href] = contents
+ elif not contents[0].startswith('&'):
+ data[contents[0]] = contents[1:]
+
+ return (headings, data)
+
+def get_soup(url):
+ content = get_url(url).readlines()
+ return BeautifulSoup(''.join(content))
+
+def crawl_outages(base_url=BASE_URL, start_url=START_URL):
+ outages = {}
+
+ # Get bunch of counties
+ countysoup = get_soup(base_url + start_url)
+ countyheadings, countydata = scrape_table(countysoup.table)
+
+ # From here, we need to get a bunch of towns...
+ for countyfile, countyrow in countydata.items():
+ townsoup = get_soup(base_url + countyfile)
+ townheadings, towndata = scrape_table(townsoup.table)
+
+ # And then a bunch of streets...
+ countydict = {}
+ for townfile, townrow in towndata.items():
+ if str(townfile) == str(start_url):
+ continue
+ towndict = {}
+ streetsoup = get_soup(base_url + townfile)
+ streetheadings, streetdata = scrape_table(streetsoup.table)
+ for streetname, streetrow in streetdata.items():
+ if str(streetname) == str(countyfile):
+ continue
+ if len(streetrow) == 2:
+ streetrow.append('Unknown')
+ towndict[streetname] = {
+ 'TotalCustomers': streetrow[0],
+ 'CustomersWithoutPower': streetrow[1],
+ 'EstimatedRestoration': streetrow[2],
+ }
+
+ countydict[townrow[0]] = {
+ 'TotalCustomers': townrow[1],
+ 'CustomersWithoutPower': townrow[2],
+ 'Streets': towndict,
+ }
+
+ outages[countyrow[0]] = {
+ 'TotalCustomers': countyrow[1],
+ 'CustomersWithoutPower': countyrow[2],
+ 'Towns': countydict,
+ }
+
+ return outages
+
+if __name__ == '__main__':
+ structure = crawl_outages(BASE_URL, START_URL)
+ print `structure`
|
rtucker/rgeoutages
|
89f01a1ac96004b2b2c4bf6545c3789abb64d22e
|
change the info text, so the google listing for this page is more useful
|
diff --git a/generate_map.py b/generate_map.py
index 4953336..4184688 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,452 +1,450 @@
#!/usr/bin/python
# vim: set fileencoding=utf-8 :
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = u"""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>(%i) Rochester, New York Power Outage Map</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % (len(markers), apikey)
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 30:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 8:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 29:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += u"""
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += u"""
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += u"""
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += u"""
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += u"""
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
# colors available:
# black, brown, green, purple, yellow, grey, orange, white
if age < 15*60:
color = 'white'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
color = 'purple'
elif age < 65*60:
color = 'orange'
elif age < 115*60:
color = 'brown'
else:
color = 'black'
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s<br>First reported: %s", "%s"));' % (lat, long, text, nicetime, color)
else:
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "grey"));' % (lat, long, text)
def produceMapBody(body):
return u""" <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist).encode("utf-8"))
bodytext = u"""
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Rochester-area Power Outage Map</b> as of %s (%i street%s)</b></p>
<p style="font-size:small;"><a href="javascript:unhide('faqbox');">More information about this map</a> |
<a href="javascript:unhide('chartbox');">Outage graph</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
- <p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
- <hr>
- <p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
+ <p>This map plots the approximate locations of power outages in Rochester, New York, and is updated every ten minutes. The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="https://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
<li><b>This page may be out of date.</b> This page does not get regenerated if there are no outages. (Pure laziness on my part.) If in doubt, check the as-of time.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
-
- <p style="font-size:xx-small;"><a href="http://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
+ <hr>
+ <p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
+ <p style="font-size:xx-small;"><a href="https://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
-
|
rtucker/rgeoutages
|
23b141d85a3786eb6b63ca4a12d9e6271c97b274
|
Fix a unicode problem in generate_map.py
|
diff --git a/generate_map.py b/generate_map.py
index ad60c67..4953336 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,451 +1,452 @@
#!/usr/bin/python
+# vim: set fileencoding=utf-8 :
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
- out = """
+ out = u"""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>(%i) Rochester, New York Power Outage Map</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % (len(markers), apikey)
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 30:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 8:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 29:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
- out += """
+ out += u"""
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
- out += """
+ out += u"""
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
- out += """
+ out += u"""
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
- out += """
+ out += u"""
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
- out += """
+ out += u"""
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
# colors available:
# black, brown, green, purple, yellow, grey, orange, white
if age < 15*60:
color = 'white'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
color = 'purple'
elif age < 65*60:
color = 'orange'
elif age < 115*60:
color = 'brown'
else:
color = 'black'
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s<br>First reported: %s", "%s"));' % (lat, long, text, nicetime, color)
else:
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "grey"));' % (lat, long, text)
def produceMapBody(body):
- return """ <body onload="initialize()" onunload="GUnload()">
+ return u""" <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
- sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
+ sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist).encode("utf-8"))
- bodytext = """
+ bodytext = u"""
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Rochester-area Power Outage Map</b> as of %s (%i street%s)</b></p>
<p style="font-size:small;"><a href="javascript:unhide('faqbox');">More information about this map</a> |
<a href="javascript:unhide('chartbox');">Outage graph</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
<li><b>This page may be out of date.</b> This page does not get regenerated if there are no outages. (Pure laziness on my part.) If in doubt, check the as-of time.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<p style="font-size:xx-small;"><a href="http://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
05c29fb88c0cfdcaafb0dd4371787b7fffa58ac4
|
reducing outlier filter distance from 50 to 30
|
diff --git a/generate_map.py b/generate_map.py
index 0be27f5..ad60c67 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,451 +1,451 @@
#!/usr/bin/python
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>(%i) Rochester, New York Power Outage Map</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % (len(markers), apikey)
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
- if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
+ if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 30:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 8:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 29:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
# colors available:
# black, brown, green, purple, yellow, grey, orange, white
if age < 15*60:
color = 'white'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
color = 'purple'
elif age < 65*60:
color = 'orange'
elif age < 115*60:
color = 'brown'
else:
color = 'black'
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s<br>First reported: %s", "%s"));' % (lat, long, text, nicetime, color)
else:
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "grey"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Rochester-area Power Outage Map</b> as of %s (%i street%s)</b></p>
<p style="font-size:small;"><a href="javascript:unhide('faqbox');">More information about this map</a> |
<a href="javascript:unhide('chartbox');">Outage graph</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
<li><b>This page may be out of date.</b> This page does not get regenerated if there are no outages. (Pure laziness on my part.) If in doubt, check the as-of time.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<p style="font-size:xx-small;"><a href="http://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
7e4a6d2d77be03b050dcd4fee630b967fa587a54
|
adding history.json and outagechart.png to .gitignore
|
diff --git a/.gitignore b/.gitignore
index 0f720b4..4b21cfa 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,7 @@
index.html
outages_*
secrets.py
*.pyc
*.sqlite3
+outagechart.png
+history.json
|
rtucker/rgeoutages
|
f68049ac08a73f6d86fec99e06690e151f82d148
|
munin server upgraded to lucid; new url
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
index b73e3b3..17266a8 100755
--- a/fetch_outages.sh
+++ b/fetch_outages.sh
@@ -1,55 +1,55 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages/
GENERATOR=$BASEDIR/generate_map.py
HTMLFILE=$BASEDIR/index.html
export TZ=America/New_York
# Test for sanity
[ -d "$BASEDIR" ] || (echo "Base directory missing: $BASEDIR"; exit 1)
[ -x "$GENERATOR" ] || (echo "Generator script not executable: $GENERATOR"; exit 1)
# Fetch location list
TEMPFILE=`tempfile`
wget -q -O $TEMPFILE http://ebiz1.rge.com/cusweb/outage/index.aspx
LOCATIONS=`grep "<option value=\"14|" $TEMPFILE | cut -d'|' -f2 | cut -d'"' -f1 | sed "s/ /%20/g" | xargs`
rm $TEMPFILE
# Fetch street data
cd $BASEDIR || (echo "Could not cd to $BASEDIR"; exit 1)
rm outages_*.txt 2>/dev/null
for i in $LOCATIONS
do
TEMPFILE=`tempfile`
OUTFILE=outages_$i.txt
wget -q -O $TEMPFILE "http://ebiz1.rge.com/cusweb/outage/roadoutages.aspx?town=$i"
grep "wcHeader_Label3" $TEMPFILE \
| cut -d'>' -f2 | cut -d'<' -f1 > $OUTFILE
grep "<td nowrap=\"nowrap\">" $TEMPFILE \
| cut -d">" -f2 | cut -d"<" -f1 >> $OUTFILE
rm $TEMPFILE
sleep 2
done
# All together now
TEMPFILE=`tempfile`
$GENERATOR $LOCATIONS > $TEMPFILE
if [ -n "`cat $TEMPFILE`" ]; then
cp $TEMPFILE $HTMLFILE
elif [ -z "$LOCATIONS" ] ; then
# there are no outages! do something cool.
true
else
echo "$TEMPFILE was empty, utoh"
fi
rm $TEMPFILE
# Fetch a munin chart
-wget -q -O outagechart.png http://hennepin.hoopycat.com/munin/hoopycat.com/framboise-rgeoutages-day.png
+wget -q -O outagechart.png http://hennepin.hoopycat.com/munin/hoopycat.com/framboise/rgeoutages-day.png
|
rtucker/rgeoutages
|
46aa42736e6598ca526f9b71d0d86b1ec2c1b175
|
adding outage count to title, cleaning up some text
|
diff --git a/generate_map.py b/generate_map.py
index 4a493a2..0be27f5 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,449 +1,451 @@
#!/usr/bin/python
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
- <title>Current Power Outage Map for Rochester, New York</title>
+ <title>(%i) Rochester, New York Power Outage Map</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
-""" % apikey
+""" % (len(markers), apikey)
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 8:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 29:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
# colors available:
# black, brown, green, purple, yellow, grey, orange, white
if age < 15*60:
color = 'white'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
color = 'purple'
elif age < 65*60:
color = 'orange'
elif age < 115*60:
color = 'brown'
else:
color = 'black'
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s<br>First reported: %s", "%s"));' % (lat, long, text, nicetime, color)
else:
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "grey"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
- <p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). See <a href="javascript:unhide('faqbox');">more information about this map</a>, or
- <a href="javascript:unhide('chartbox');">view a graph</a> of recent power outage totals.</p>
+ <p><b>Rochester-area Power Outage Map</b> as of %s (%i street%s)</b></p>
+ <p style="font-size:small;"><a href="javascript:unhide('faqbox');">More information about this map</a> |
+ <a href="javascript:unhide('chartbox');">Outage graph</a></p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
+ <li><b>This page may be out of date.</b> This page does not get regenerated if there are no outages. (Pure laziness on my part.) If in doubt, check the as-of time.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
- <p><a href="http://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
+ <p style="font-size:xx-small;"><a href="http://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
cce47f07a93ee00c7ad388d2ae259f64d50d8cd9
|
another zoom adjustment
|
diff --git a/generate_map.py b/generate_map.py
index 28f8ed3..4a493a2 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,449 +1,449 @@
#!/usr/bin/python
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 8:
zoom = 13
elif distance < 13:
zoom = 12
- elif distance < 25:
+ elif distance < 29:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
# colors available:
# black, brown, green, purple, yellow, grey, orange, white
if age < 15*60:
color = 'white'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
color = 'purple'
elif age < 65*60:
color = 'orange'
elif age < 115*60:
color = 'brown'
else:
color = 'black'
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s<br>First reported: %s", "%s"));' % (lat, long, text, nicetime, color)
else:
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "grey"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). See <a href="javascript:unhide('faqbox');">more information about this map</a>, or
<a href="javascript:unhide('chartbox');">view a graph</a> of recent power outage totals.</p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<p><a href="http://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
090ee07fba895f460bd2a6d885590e195712606a
|
more zoom tweaking, also found red is not an explicitly available option for color
|
diff --git a/generate_map.py b/generate_map.py
index 3942b22..28f8ed3 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,445 +1,449 @@
#!/usr/bin/python
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
- elif distance < 11:
+ elif distance < 8:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 25:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
+ # colors available:
+ # black, brown, green, purple, yellow, grey, orange, white
if age < 15*60:
- color = 'purple'
+ color = 'white'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
+ color = 'purple'
+ elif age < 65*60:
color = 'orange'
elif age < 115*60:
- color = 'red'
+ color = 'brown'
else:
color = 'black'
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s<br>First reported: %s", "%s"));' % (lat, long, text, nicetime, color)
else:
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "grey"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). See <a href="javascript:unhide('faqbox');">more information about this map</a>, or
<a href="javascript:unhide('chartbox');">view a graph</a> of recent power outage totals.</p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<p><a href="http://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
ac7ac004eed83df670053d98b4e97d7de9b74e98
|
zoom adjustment
|
diff --git a/generate_map.py b/generate_map.py
index d8c8002..3942b22 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,447 +1,445 @@
#!/usr/bin/python
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
- elif distance < 7:
- zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 25:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
if age < 15*60:
color = 'purple'
elif age < 25*60:
color = 'green'
elif age < 35*60:
color = 'yellow'
elif age < 45*60:
color = 'orange'
elif age < 115*60:
color = 'red'
else:
color = 'black'
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s<br>First reported: %s", "%s"));' % (lat, long, text, nicetime, color)
else:
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "grey"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). See <a href="javascript:unhide('faqbox');">more information about this map</a>, or
<a href="javascript:unhide('chartbox');">view a graph</a> of recent power outage totals.</p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<p><a href="http://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
5772c45b49868b2e5514be7ec0666a0988d90561
|
huh, there is no blue google maps marker. also adjusting timings for color decay
|
diff --git a/generate_map.py b/generate_map.py
index 563b54b..d8c8002 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,447 +1,447 @@
#!/usr/bin/python
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 25:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
- if age < 10*60:
+ if age < 15*60:
color = 'purple'
- elif age < 20*60:
- color = 'blue'
- elif age < 30*60:
+ elif age < 25*60:
color = 'green'
- elif age < 40*60:
+ elif age < 35*60:
color = 'yellow'
- elif age < 50*60:
+ elif age < 45*60:
color = 'orange'
- else:
+ elif age < 115*60:
color = 'red'
+ else:
+ color = 'black'
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s<br>First reported: %s", "%s"));' % (lat, long, text, nicetime, color)
else:
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "grey"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). See <a href="javascript:unhide('faqbox');">more information about this map</a>, or
<a href="javascript:unhide('chartbox');">view a graph</a> of recent power outage totals.</p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<p><a href="http://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
35573748242e2e5a094d57783d83d3b1613a755a
|
dont add citycenters to the points list, to avoid throwing off zoom
|
diff --git a/generate_map.py b/generate_map.py
index cf79f2e..563b54b 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,448 +1,447 @@
#!/usr/bin/python
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
minLng = -76.1
maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 25:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
if age < 10*60:
color = 'purple'
elif age < 20*60:
color = 'blue'
elif age < 30*60:
color = 'green'
elif age < 40*60:
color = 'yellow'
elif age < 50*60:
color = 'orange'
else:
color = 'red'
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s<br>First reported: %s", "%s"));' % (lat, long, text, nicetime, color)
else:
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "grey"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
- pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). See <a href="javascript:unhide('faqbox');">more information about this map</a>, or
<a href="javascript:unhide('chartbox');">view a graph</a> of recent power outage totals.</p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<p><a href="http://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
9af82fc2ef5fd4f6ea59eec5f871af6af2a62172
|
those pesky negative numbers... switching the order of the min/max longitude initialization numbers
|
diff --git a/generate_map.py b/generate_map.py
index ca03b31..cf79f2e 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,448 +1,448 @@
#!/usr/bin/python
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 44.9
maxLat = 42.1
- minLng = -78.9
- maxLng = -76.1
+ minLng = -76.1
+ maxLng = -78.9
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 25:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
if age < 10*60:
color = 'purple'
elif age < 20*60:
color = 'blue'
elif age < 30*60:
color = 'green'
elif age < 40*60:
color = 'yellow'
elif age < 50*60:
color = 'orange'
else:
color = 'red'
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s<br>First reported: %s", "%s"));' % (lat, long, text, nicetime, color)
else:
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "grey"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). See <a href="javascript:unhide('faqbox');">more information about this map</a>, or
<a href="javascript:unhide('chartbox');">view a graph</a> of recent power outage totals.</p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<p><a href="http://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
7eaed18362e95e346e3e3999a96e37acd66152c8
|
need to export the TZ variable
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
index 8c28402..b73e3b3 100755
--- a/fetch_outages.sh
+++ b/fetch_outages.sh
@@ -1,55 +1,55 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages/
GENERATOR=$BASEDIR/generate_map.py
HTMLFILE=$BASEDIR/index.html
-TZ=America/New_York
+export TZ=America/New_York
# Test for sanity
[ -d "$BASEDIR" ] || (echo "Base directory missing: $BASEDIR"; exit 1)
[ -x "$GENERATOR" ] || (echo "Generator script not executable: $GENERATOR"; exit 1)
# Fetch location list
TEMPFILE=`tempfile`
wget -q -O $TEMPFILE http://ebiz1.rge.com/cusweb/outage/index.aspx
LOCATIONS=`grep "<option value=\"14|" $TEMPFILE | cut -d'|' -f2 | cut -d'"' -f1 | sed "s/ /%20/g" | xargs`
rm $TEMPFILE
# Fetch street data
cd $BASEDIR || (echo "Could not cd to $BASEDIR"; exit 1)
rm outages_*.txt 2>/dev/null
for i in $LOCATIONS
do
TEMPFILE=`tempfile`
OUTFILE=outages_$i.txt
wget -q -O $TEMPFILE "http://ebiz1.rge.com/cusweb/outage/roadoutages.aspx?town=$i"
grep "wcHeader_Label3" $TEMPFILE \
| cut -d'>' -f2 | cut -d'<' -f1 > $OUTFILE
grep "<td nowrap=\"nowrap\">" $TEMPFILE \
| cut -d">" -f2 | cut -d"<" -f1 >> $OUTFILE
rm $TEMPFILE
sleep 2
done
# All together now
TEMPFILE=`tempfile`
$GENERATOR $LOCATIONS > $TEMPFILE
if [ -n "`cat $TEMPFILE`" ]; then
cp $TEMPFILE $HTMLFILE
elif [ -z "$LOCATIONS" ] ; then
# there are no outages! do something cool.
true
else
echo "$TEMPFILE was empty, utoh"
fi
rm $TEMPFILE
# Fetch a munin chart
wget -q -O outagechart.png http://hennepin.hoopycat.com/munin/hoopycat.com/framboise-rgeoutages-day.png
|
rtucker/rgeoutages
|
49d6be10b69d6048760c27a4242ae8b4e646c24d
|
adjust the min/max lat/lng variable initialization so that the first point always throws it
|
diff --git a/generate_map.py b/generate_map.py
index 31dc65b..ca03b31 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,448 +1,448 @@
#!/usr/bin/python
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
- minLat = 43.15661
- maxLat = 43.15661
- minLng = -77.6253
- maxLng = -77.6253
+ minLat = 44.9
+ maxLat = 42.1
+ minLng = -78.9
+ maxLng = -76.1
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 25:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
def produceMarker(lat, long, text, firstreport=-1):
"""Produces a google maps marker given a latitude, longitude, text, and first report time"""
if firstreport > 0:
age = time.time()-firstreport
nicetime = time.asctime(time.localtime(firstreport))
if age < 10*60:
color = 'purple'
elif age < 20*60:
color = 'blue'
elif age < 30*60:
color = 'green'
elif age < 40*60:
color = 'yellow'
elif age < 50*60:
color = 'orange'
else:
color = 'red'
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s<br>First reported: %s", "%s"));' % (lat, long, text, nicetime, color)
else:
return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "grey"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
try:
# open the history file (how long current outages have been there)
historyfd = open('history.json','r')
historydict = json.load(historyfd)
historyfd.close()
except IOError:
historydict = {}
newhistorydict = {}
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
if streetinfo['formattedaddress'] in historydict.keys():
firstreport = historydict[streetinfo['formattedaddress']]
else:
firstreport = time.time()
markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport))
pointlist.append(streetinfo)
newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
newhistoryfd = open('history.json','w')
json.dump(newhistorydict, newhistoryfd)
newhistoryfd.close()
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). See <a href="javascript:unhide('faqbox');">more information about this map</a>, or
<a href="javascript:unhide('chartbox');">view a graph</a> of recent power outage totals.</p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<p><a href="http://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
rtucker/rgeoutages
|
aa47baf164a76f37365ce52c717d6b7c29448077
|
forcing the timezone to America/New_York (GMT is kinda useless here)
|
diff --git a/fetch_outages.sh b/fetch_outages.sh
index 53660fb..8c28402 100755
--- a/fetch_outages.sh
+++ b/fetch_outages.sh
@@ -1,54 +1,55 @@
#!/bin/bash
BASEDIR=/var/www/hoopycat.com/html/rgeoutages/
GENERATOR=$BASEDIR/generate_map.py
HTMLFILE=$BASEDIR/index.html
+TZ=America/New_York
# Test for sanity
[ -d "$BASEDIR" ] || (echo "Base directory missing: $BASEDIR"; exit 1)
[ -x "$GENERATOR" ] || (echo "Generator script not executable: $GENERATOR"; exit 1)
# Fetch location list
TEMPFILE=`tempfile`
wget -q -O $TEMPFILE http://ebiz1.rge.com/cusweb/outage/index.aspx
LOCATIONS=`grep "<option value=\"14|" $TEMPFILE | cut -d'|' -f2 | cut -d'"' -f1 | sed "s/ /%20/g" | xargs`
rm $TEMPFILE
# Fetch street data
cd $BASEDIR || (echo "Could not cd to $BASEDIR"; exit 1)
rm outages_*.txt 2>/dev/null
for i in $LOCATIONS
do
TEMPFILE=`tempfile`
OUTFILE=outages_$i.txt
wget -q -O $TEMPFILE "http://ebiz1.rge.com/cusweb/outage/roadoutages.aspx?town=$i"
grep "wcHeader_Label3" $TEMPFILE \
| cut -d'>' -f2 | cut -d'<' -f1 > $OUTFILE
grep "<td nowrap=\"nowrap\">" $TEMPFILE \
| cut -d">" -f2 | cut -d"<" -f1 >> $OUTFILE
rm $TEMPFILE
sleep 2
done
# All together now
TEMPFILE=`tempfile`
$GENERATOR $LOCATIONS > $TEMPFILE
if [ -n "`cat $TEMPFILE`" ]; then
cp $TEMPFILE $HTMLFILE
elif [ -z "$LOCATIONS" ] ; then
# there are no outages! do something cool.
true
else
echo "$TEMPFILE was empty, utoh"
fi
rm $TEMPFILE
# Fetch a munin chart
wget -q -O outagechart.png http://hennepin.hoopycat.com/munin/hoopycat.com/framboise-rgeoutages-day.png
|
rtucker/rgeoutages
|
36f22aa4b94d4a684c8122399521a5e3a455bbfe
|
keep track of when outages were created and change the icon color depending on age
|
diff --git a/generate_map.py b/generate_map.py
index a6325e0..31dc65b 100755
--- a/generate_map.py
+++ b/generate_map.py
@@ -1,413 +1,448 @@
#!/usr/bin/python
import math
import os
import sqlite3
import sys
import time
import urllib
import urllib2
try:
import json
except:
import simplejson as json
try:
import secrets
except:
sys.stderr.write("You need to create a secrets.py file with a Google Maps API key.")
sys.exit(1)
def initDB(filename="rgeoutages.sqlite3"):
"""Connect to and initialize the cache database.
Optional: Filename of database
Returns: db object
"""
db = sqlite3.connect(filename)
c = db.cursor()
c.execute('pragma table_info(geocodecache)')
columns = ' '.join(i[1] for i in c.fetchall()).split()
if columns == []:
# need to create table
c.execute("""create table geocodecache
(town text, streetname text, latitude real, longitude real,
formattedaddress text, locationtype text, lastcheck integer,
viewport text)""")
db.commit()
return db
def fetchGeocode(location):
"""Fetches geocoding information.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
sanelocation = urllib.quote(location)
response = urllib2.urlopen("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % sanelocation)
jsondata = response.read()
jsondict = json.loads(jsondata)
if jsondict['results'] == []:
raise Exception("Empty results string: " + jsondict['status'])
data = jsondict['results'][0]
viewport = ( data['geometry']['viewport']['southwest']['lat'],
data['geometry']['viewport']['southwest']['lng'],
data['geometry']['viewport']['northeast']['lat'],
data['geometry']['viewport']['northeast']['lng'] )
outdict = { 'formattedaddress': data['formatted_address'],
'latitude': data['geometry']['location']['lat'],
'longitude': data['geometry']['location']['lng'],
'locationtype': data['geometry']['location_type'],
'viewport': viewport }
time.sleep(1)
return outdict
def geocode(db, town, location):
"""Geocodes a location, either using the cache or the Google.
Returns dictionary of formattedaddress, latitude, longitude,
locationtype, and viewport tuple of (sw_lat, sw_lng, ne_lat, ne_lng).
"""
town = town.lower().strip()
location = location.lower().strip()
using_cache = False
# check the db
c = db.cursor()
c.execute('select latitude,longitude,formattedaddress,locationtype,viewport,lastcheck from geocodecache where town=? and streetname=? order by lastcheck desc limit 1', (town, location))
rows = c.fetchall()
if rows:
(latitude,longitude,formattedaddress,locationtype,viewport_json,lastcheck) = rows[0]
if lastcheck < (time.time()+(7*24*60*60)):
using_cache = True
viewport = tuple(json.loads(viewport_json))
outdict = { 'formattedaddress': formattedaddress,
'latitude': latitude,
'longitude': longitude,
'locationtype': locationtype,
'viewport': viewport }
return outdict
if not using_cache:
fetchresult = fetchGeocode(location + ", " + town + " NY")
viewport_json = json.dumps(fetchresult['viewport'])
c.execute('insert into geocodecache (town, streetname, latitude, longitude, formattedaddress, locationtype, lastcheck, viewport) values (?,?,?,?,?,?,?,?)', (town, location, fetchresult['latitude'], fetchresult['longitude'], fetchresult['formattedaddress'], fetchresult['locationtype'], time.time(), viewport_json))
db.commit()
return fetchresult
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# From http://www.johndcook.com/python_longitude_latitude.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
return arc
def produceMapHeader(apikey, markers, centers, points):
"""Produces a map header given an API key and a list of produceMarkers"""
out = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="600"/>
<title>Current Power Outage Map for Rochester, New York</title>
<style type="text/css">
v\:* {behavior:url(#default#VML);} html, body {width: 100%%; height: 100%%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px}
p, li {
font-family: Verdana, sans-serif;
font-size: 13px;
}
a {
text-decoration: none;
}
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
</style>
<script src="http://maps.google.com/maps?file=api&v=2&key=%s" type="text/javascript"></script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script>
<script type="text/javascript">
function hide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='unhidden')?'hidden':'unhidden';
}
}
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
var map = null;
var mgr = null;
- function createMarker(point, text) {
+ function createMarker(point, text, color) {
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
var ouricon = new GIcon(baseIcon);
- ouricon.image = "http://www.google.com/mapfiles/marker.png";
+ ouricon.image = "http://www.google.com/mapfiles/marker_" + color + ".png";
// Set up our GMarkerOptions object
markerOptions = { icon:ouricon };
var marker = new GMarker(point, markerOptions);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
""" % apikey
# Determine center of map:
# Initialize variables
minLat = 43.15661
maxLat = 43.15661
minLng = -77.6253
maxLng = -77.6253
# Iterate through and expand the range, ignoring outliers
for i in points:
if distance_on_unit_sphere((minLat+maxLat)/2, (minLng+maxLng)/2, i['latitude'], i['longitude'])*3960 < 50:
minLat = min(i['latitude'], minLat)
maxLat = max(i['latitude'], maxLat)
minLng = min(i['longitude'], minLng)
maxLng = max(i['longitude'], maxLng)
# Calculate center
centerLat = (minLat + maxLat) / 2
centerLng = (minLng + maxLng) / 2
# Guestimate zoom by finding diagonal distance (in miles)
distance = distance_on_unit_sphere(minLat, minLng, maxLat, maxLng) * 3960
if distance < 5:
zoom = 15
elif distance < 7:
zoom = 14
elif distance < 11:
zoom = 13
elif distance < 13:
zoom = 12
elif distance < 25:
zoom = 11
elif distance < 35:
zoom = 10
else:
zoom = 9
if len(markers) > 300:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 12);
var batch = [];
%s
mgr.addMarkers(batch, 1, 12);
mgr.refresh();
}
""" % ('\n'.join(markers), '\n'.join(centers))
zoom = min(zoom, 11)
else:
out += """
function setupMarkers() {
var batch = [];
%s
mgr.addMarkers(batch, 1);
mgr.refresh();
}
""" % '\n'.join(markers)
out += """
/* distance: %.2f
minimum corner: %.4f, %.4f
maximum corner: %.4f, %.4f */
""" % (distance, minLat, minLng, maxLat, maxLng)
out += """
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(%.4f, %.4f), %i);
map.setUIToDefault();
mgr = new MarkerManager(map);
window.setTimeout(setupMarkers, 0);
// Monitor the window resize event and let the map know when it occurs
if (window.attachEvent) {
window.attachEvent("onresize", function() {this.map.onResize()} );
} else {
window.addEventListener("resize", function() {this.map.onResize()} , false);
}
}
} """ % (centerLat, centerLng, zoom)
out += """
</script>
</head>
"""
return out
-def produceMarker(lat, long, text):
- """Produces a google maps marker given a latitude, longitude, and text"""
- return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s"));' % (lat, long, text)
+def produceMarker(lat, long, text, firstreport=-1):
+ """Produces a google maps marker given a latitude, longitude, text, and first report time"""
+ if firstreport > 0:
+ age = time.time()-firstreport
+ nicetime = time.asctime(time.localtime(firstreport))
+ if age < 10*60:
+ color = 'purple'
+ elif age < 20*60:
+ color = 'blue'
+ elif age < 30*60:
+ color = 'green'
+ elif age < 40*60:
+ color = 'yellow'
+ elif age < 50*60:
+ color = 'orange'
+ else:
+ color = 'red'
+ return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s<br>First reported: %s", "%s"));' % (lat, long, text, nicetime, color)
+ else:
+ return 'batch.push(new createMarker(new GLatLng(%f, %f), "%s", "grey"));' % (lat, long, text)
def produceMapBody(body):
return """ <body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 100%%; height: 100%%;"></div>
%s
</body>
</html>
""" % body
if __name__ == '__main__':
db = initDB()
try:
apikey = secrets.apikey
except:
apikey = 'FIXME FIXME FIXME'
localelist = []
markerlist = []
citycenterlist = []
pointlist = []
stoplist = ['HONEOYE%20FL', 'HONEOYE', 'N%20CHILI']
git_version = open('.git/refs/heads/master','r').read()
git_modtime = time.asctime(time.localtime(os.stat('.git/refs/heads/master').st_mtime))
+ try:
+ # open the history file (how long current outages have been there)
+ historyfd = open('history.json','r')
+ historydict = json.load(historyfd)
+ historyfd.close()
+ except IOError:
+ historydict = {}
+ newhistorydict = {}
+
for i in sys.argv[1:]:
if i in stoplist:
continue
fd = open('outages_%s.txt' % i)
lastupdated = fd.readline()
cleanname = i.replace('%20', ' ')
count = 0
citycenter = geocode(db, cleanname, '')
citycenterlist.append(produceMarker(citycenter['latitude'], citycenter['longitude'], citycenter['formattedaddress']))
pointlist.append(citycenter)
for j in fd.readlines():
try:
streetinfo = geocode(db, cleanname, j)
- markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress']))
+ if streetinfo['formattedaddress'] in historydict.keys():
+ firstreport = historydict[streetinfo['formattedaddress']]
+ else:
+ firstreport = time.time()
+ markerlist.append(produceMarker(streetinfo['latitude'], streetinfo['longitude'], streetinfo['formattedaddress'], firstreport))
pointlist.append(streetinfo)
+ newhistorydict[streetinfo['formattedaddress']] = firstreport
count += 1
except Exception, e:
sys.stdout.write("<!-- Geocode fail: %s in %s gave %s -->\n" % (j, cleanname, e.__str__()))
if count > 1:
s = 's'
else:
s = ''
localelist.append('<a href="http://ebiz1.rge.com/cusweb/outage/roadOutages.aspx?town=%s">%s</a>: %i street%s' % (i, cleanname, count, s))
+ newhistoryfd = open('history.json','w')
+ json.dump(newhistorydict, newhistoryfd)
+ newhistoryfd.close()
+
if len(markerlist) > 0:
if len(markerlist) > 300:
s = 's -- zoom for more detail'
elif len(markerlist) > 1:
s = 's'
else:
s = ''
sys.stdout.write(produceMapHeader(apikey, markerlist, citycenterlist, pointlist))
bodytext = """
<div id="infobox" class="unhidden" style="top:25px; left:75px; position:absolute; background-color:white; border:2px solid black; width:50%%; opacity:0.8; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('infobox');"><img src="xbox.png" border=0 alt="X" title="We'll leave the light on for you."></a>
</div>
<p><b>Map of Rochester-area Power Outages</b> as of %s (%i street%s). See <a href="javascript:unhide('faqbox');">more information about this map</a>, or
<a href="javascript:unhide('chartbox');">view a graph</a> of recent power outage totals.</p>
<p style="font-size:xx-small;">%s</p>
</div>
<div id="faqbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; width:75%%; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('faqbox');"><img src="xbox.png" border=0 alt="X" title="OK, OK, I'll show you the map."></a>
</div>
<p><b>IF YOU HAVE A LIFE-THREATENING ELECTRICAL EMERGENCY, CALL RG&E AT 1-800-743-1701 OR CALL 911 IMMEDIATELY. DO NOT TOUCH DOWNED ELECTRICAL LINES, EVER. EVEN IF YOUR STREET IS LISTED HERE.</b></p>
<hr>
<p>The source data for this map is published by <A HREF="http://ebiz1.rge.com/cusweb/outage/index.aspx">RG&E</A>, but all map-related blame should go to <a href="http://hoopycat.com/~rtucker/">Ryan Tucker</a> <<a href="mailto:[email protected]">[email protected]</a>>. You can find the source code <a href="http://github.com/rtucker/rgeoutages/">on GitHub</a>.</p>
<p>Some important tips to keep in mind...</p>
<ul>
<li><b>RG&E only publishes a list of street names.</b> This map's pointer will end up in the geographic center of the street, which will undoubtedly be wrong for really long streets. Look for clusters of outages.</li>
<li><b>This map doesn't indicate the actual quantity of power outages or people without power.</b> There may be just one house without power on a street, or every house on a street. There may be multiple unrelated outages on one street, too. There's no way to know.</li>
</ul>
<p>Also, be sure to check out RG&E's <a href="http://rge.com/Outages/">Outage Central</a> for official information, to report outages, or to check on the status of an outage.</p>
<p><a href="http://github.com/rtucker/rgeoutages/commit/%s">Software last modified %s</a>.</p>
</div>
<div id="chartbox" class="hidden" style="top:45px; left:95px; position:absolute; background-color:white; border:2px solid black; padding:10px;">
<div id="closebutton" style="top:2px; right:2px; position:absolute">
<a href="javascript:hide('chartbox');"><img src="xbox.png" border=0 alt="X" title="Hide graph window"></a>
</div>
<div id="graphimage" style="background:url(outagechart.png); width:495px; height:271px;"></div>
</div>
""" % (lastupdated, len(markerlist), s, '; '.join(localelist), git_version, git_modtime)
sys.stdout.write(produceMapBody(bodytext))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.