repo
string | commit
string | message
string | diff
string |
---|---|---|---|
wilkerlucio/jquery-multiselect
|
407a2e39f47cfc5b878634c2812254765f121403
|
replacing multiple select
|
diff --git a/examples/index.html b/examples/index.html
index 3e602a3..e18bfea 100644
--- a/examples/index.html
+++ b/examples/index.html
@@ -1,42 +1,48 @@
<!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" xml:lang="en">
<head>
<title>JqueryMultiSelect Example</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="../css/jquery.multiselect.css" media="all">
<script type="text/javascript" src="../vendor/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../js/jquery.multiselect.js"></script>
<script type="text/javascript">
names = [
"Alejandra Pizarnik",
["Alicia Partnoy", "alicia"],
{caption: "Andres Rivera", value: "andres"},
"Antonio Porchia",
"Arturo Andres Roig",
"Felipe Pigna",
"Gustavo Nielsen",
"Hector German Oesterheld",
"Juan Carlos Portantiero",
"Juan L. Ortiz",
"Manuel Mujica Lainez",
"Manuel Puig",
"Mario Rodriguez Cobos",
"Olga Orozco",
"Osvaldo Tierra",
"Ricardo Piglia",
"Ricardo Rojas",
"Roberto Payro",
"Silvina Ocampo",
"Victoria Ocampo",
"Zuriel Barron"
]
$(function() {
$("#sample-tags").multiselect({completions: names});
+ $("#sample-select").multiselect();
});
</script>
</head>
<body>
<input type="text" name="tags" id="sample-tags" value="initial,values" />
+ <select multiple="multiple" size="5" id="sample-select" name="sample-select">
+ <option value="car">Car</option>
+ <option value="ship">Ship</option>
+ <option value="bus">Bus</option>
+ </select>
</body>
</html>
\ No newline at end of file
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index 9295c60..f8157e3 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,521 +1,542 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
BACKSPACE: 8,
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ",",
completions: [],
max_complete_results: 5,
enable_new_options: true
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
this.parse_value();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
return this.parse_value(1);
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
if (this.autocomplete.val()) {
e.preventDefault();
return this.add_and_reset();
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.observer.bind([KEY.BACKSPACE], (function(__this) {
var __func = function(e) {
var caret;
if (this.values.length <= 0) {
return null;
}
caret = this.selection.get_caret();
if (caret[0] === 0 && caret[1] === 0) {
e.preventDefault();
return this.remove(this.values[this.values.length - 1]);
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.prototype.values_real = function values_real() {
return $.map(this.values, function(v) {
return v[1];
});
};
$.MultiSelect.prototype.parse_value = function parse_value(min) {
var _a, _b, _c, value, values;
min = (typeof min !== "undefined" && min !== null) ? min : 0;
values = this.input.val().split(this.options.separator);
if (values.length > min) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.present()) {
this.add([value, value]);
}
}
this.input.val("");
return this.autocomplete.search();
}
};
$.MultiSelect.prototype.add_and_reset = function add_and_reset() {
if (this.autocomplete.val()) {
this.add(this.autocomplete.val());
this.input.val("");
return this.autocomplete.search();
}
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value[1], this.values_real()) > -1) {
return null;
}
if (value[0].blank()) {
return null;
}
value[1] = value[1].trim();
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
a.html(value[0].entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
return this.remove(a.data("value"));
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
console.log(this.values);
this.values = $.grep(this.values, function(v) {
return v[1] !== value[1];
});
this.container.find("a.bit-box").each(function() {
if ($(this).data("value")[1] === value[1]) {
return $(this).remove();
}
});
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values_real().join(this.options.separator));
};
// Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
// Selection Helper
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
var r;
// For IE
if (document.selection) {
r = document.selection.createRange().duplicate();
r.moveEnd('character', this.input.value.length);
if (r.text === '') {
return [this.input.value.length, this.input.value.length];
} else {
return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)];
// Others
}
} else {
return [this.input.selectionStart, this.input.selectionEnd];
}
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
// Resizable Input Helper
$.MultiSelect.ResizableInput = function ResizableInput(element) {
this.input = $(element);
this.create_measurer();
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
return this;
};
$.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
var measurer;
if ($("#__jquery_multiselect_measurer")[0] === undefined) {
measurer = $(document.createElement("div"));
measurer.attr("id", "__jquery_multiselect_measurer");
measurer.css({
position: "absolute",
left: "-1000px",
top: "-1000px"
});
$(document.body).append(measurer);
}
this.measurer = $("#__jquery_multiselect_measurer:first");
return this.measurer.css({
fontSize: this.input.css('font-size'),
fontFamily: this.input.css('font-family')
});
};
$.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
this.measurer.html(this.input.val().entitizeHTML() + 'MM');
return this.measurer.innerWidth();
};
$.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
return this.input.css("width", this.calculate_width() + "px");
};
// AutoComplete Helper
$.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) {
this.multiselect = multiselect;
this.input = this.multiselect.input;
this.completions = this.parse_completions(completions);
this.matches = [];
this.create_elements();
this.bind_events();
return this;
};
$.MultiSelect.AutoComplete.prototype.parse_completions = function parse_completions(completions) {
return $.map(completions, function(value) {
if (typeof value === "string") {
return [[value, value]];
} else if (value instanceof Array && value.length === 2) {
return [value];
} else if (value.value && value.caption) {
return [[value.caption, value.value]];
} else if (console) {
return console.error("Invalid option " + (value));
}
});
};
$.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() {
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect-autocomplete");
this.container.css("width", this.multiselect.container.outerWidth());
this.container.css("display", "none");
this.container.append(this.def);
this.list = $(document.createElement("ul"));
this.list.addClass("feed");
this.container.append(this.list);
return this.multiselect.container.after(this.container);
};
$.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() {
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.multiselect.observer.bind(KEY.UP, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_up();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.multiselect.observer.bind(KEY.DOWN, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_down();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.AutoComplete.prototype.search = function search() {
var _a, _b, def, i, item, option;
if (this.input.val().trim() === this.query) {
return null;
}
// dont do operation if query is same
this.query = this.input.val().trim();
this.list.html("");
// clear list
this.current = 0;
if (this.query.present()) {
this.container.css("display", "block");
this.matches = this.matching_completions(this.query);
if (this.multiselect.options.enable_new_options) {
def = this.create_item("Add <em>" + this.query + "</em>");
def.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [0])));
}
_a = this.matches;
for (i = 0, _b = _a.length; i < _b; i++) {
option = _a[i];
item = this.create_item(this.highlight(option[0], this.query));
item.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [i + 1])));
}
if (this.multiselect.options.enable_new_options) {
this.matches.unshift([this.query, this.query]);
}
return this.select_index(0);
} else {
this.matches = [];
this.container.css("display", "none");
this.query = null;
return this.query;
}
};
$.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) {
var items;
items = this.list.find("li");
items.removeClass("auto-focus");
items.filter(":eq(" + (index) + ")").addClass("auto-focus");
this.current = index;
return this.current;
};
$.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() {
var next;
next = this.current + 1;
if (next >= this.matches.length) {
next = 0;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() {
var next;
next = this.current - 1;
if (next < 0) {
next = this.matches.length - 1;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) {
var item;
item = $(document.createElement("li"));
item.click((function(__this) {
var __func = function() {
this.multiselect.add_and_reset();
this.search();
return this.input.focus();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
item.html(text);
this.list.append(item);
return item;
};
$.MultiSelect.AutoComplete.prototype.val = function val() {
return this.matches[this.current];
};
$.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) {
var reg;
reg = "(" + (RegExp.escape(highlight)) + ")";
return text.replace(new RegExp(reg, "gi"), '<em>$1</em>');
};
$.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) {
var count, reg;
reg = new RegExp(RegExp.escape(text), "i");
count = 0;
return $.grep(this.completions, (function(__this) {
var __func = function(c) {
if (count >= this.multiselect.options.max_complete_results) {
return false;
}
if ($.inArray(c[1], this.multiselect.values_real()) > -1) {
return false;
}
if (c[0].match(reg)) {
count++;
return true;
} else {
return false;
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// Hook jQuery extension
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
- return new $.MultiSelect(this, options);
+ var _a, _b, _c, completions, input, option, select_options;
+ if (this.tagName.toLowerCase() === "select") {
+ input = $(document.createElement("input"));
+ input.attr("type", "text");
+ input.attr("name", this.name);
+ input.attr("id", this.id);
+ completions = [];
+ _b = this.options;
+ for (_a = 0, _c = _b.length; _a < _c; _a++) {
+ option = _b[_a];
+ completions.push([option.innerHTML, option.value]);
+ }
+ select_options = {
+ completions: completions,
+ enable_new_options: false
+ };
+ $.extend(select_options, options);
+ $(this).replaceWith(input);
+ return new $.MultiSelect(input, select_options);
+ } else if (this.tagName.toLowerCase() === "input" && this.type === "text") {
+ return new $.MultiSelect(this, options);
+ }
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
trim: function trim() {
return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '');
},
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
blank: function blank() {
return this.trim().length === 0;
},
present: function present() {
return !this.blank();
}
});
RegExp.escape = function escape(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index 48fd9b0..46adcbc 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,361 +1,382 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
BACKSPACE: 8
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
completions: []
max_complete_results: 5
enable_new_options: true
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
@parse_value()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection: new $.MultiSelect.Selection(@input)
@resizable: new $.MultiSelect.ResizableInput(@input)
@observer: new $.MultiSelect.InputObserver(@input)
@autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
@parse_value(1)
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
if @autocomplete.val()
e.preventDefault()
@add_and_reset()
@observer.bind [KEY.BACKSPACE], (e) =>
return if @values.length <= 0
caret = @selection.get_caret()
if caret[0] == 0 and caret[1] == 0
e.preventDefault()
@remove(@values[@values.length - 1])
values_real: ->
$.map @values, (v) -> v[1]
parse_value: (min) ->
min ?= 0
values: @input.val().split(@options.separator)
if values.length > min
for value in values
@add [value, value] if value.present()
@input.val("")
@autocomplete.search()
add_and_reset: ->
if @autocomplete.val()
@add(@autocomplete.val())
@input.val("")
@autocomplete.search()
# add new element
add: (value) ->
return if $.inArray(value[1], @values_real()) > -1
return if value[0].blank()
value[1] = value[1].trim()
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
a.html(value[0].entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
console.log @values
@values: $.grep @values, (v) -> v[1] != value[1]
@container.find("a.bit-box").each ->
$(this).remove() if $(this).data("value")[1] == value[1]
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values_real().join(@options.separator))
# Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
# Selection Helper
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
# For IE
if document.selection
r: document.selection.createRange().duplicate()
r.moveEnd('character', @input.value.length)
if r.text == ''
[@input.value.length, @input.value.length]
else
[@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)]
# Others
else
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart: begin
@input.selectionEnd: end
set_caret_at_end: ->
@set_caret(@input.value.length)
# Resizable Input Helper
class $.MultiSelect.ResizableInput
constructor: (element) ->
@input: $(element)
@create_measurer()
@input.keypress(@set_width <- this)
@input.keyup(@set_width <- this)
@input.change(@set_width <- this)
create_measurer: ->
if $("#__jquery_multiselect_measurer")[0] == undefined
measurer: $(document.createElement("div"))
measurer.attr("id", "__jquery_multiselect_measurer")
measurer.css {
position: "absolute"
left: "-1000px"
top: "-1000px"
}
$(document.body).append(measurer)
@measurer: $("#__jquery_multiselect_measurer:first")
@measurer.css {
fontSize: @input.css('font-size')
fontFamily: @input.css('font-family')
}
calculate_width: ->
@measurer.html(@input.val().entitizeHTML() + 'MM')
@measurer.innerWidth()
set_width: ->
@input.css("width", @calculate_width() + "px")
# AutoComplete Helper
class $.MultiSelect.AutoComplete
constructor: (multiselect, completions) ->
@multiselect: multiselect
@input: @multiselect.input
@completions: @parse_completions(completions)
@matches: []
@create_elements()
@bind_events()
parse_completions: (completions) ->
$.map completions, (value) ->
if typeof value == "string"
[[value, value]]
else if value instanceof Array and value.length == 2
[value]
else if value.value and value.caption
[[value.caption, value.value]]
else
console.error "Invalid option ${value}" if console
create_elements: ->
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect-autocomplete")
@container.css("width", @multiselect.container.outerWidth())
@container.css("display", "none")
@container.append(@def)
@list: $(document.createElement("ul"))
@list.addClass("feed")
@container.append(@list)
@multiselect.container.after(@container)
bind_events: ->
@input.keypress(@search <- this)
@input.keyup(@search <- this)
@input.change(@search <- this)
@multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up()
@multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down()
search: ->
return if @input.val().trim() == @query # dont do operation if query is same
@query: @input.val().trim()
@list.html("") # clear list
@current: 0
if @query.present()
@container.css("display", "block")
@matches: @matching_completions(@query)
if @multiselect.options.enable_new_options
def: @create_item("Add <em>" + @query + "</em>")
def.mouseover(@select_index <- this, 0)
for option, i in @matches
item: @create_item(@highlight(option[0], @query))
item.mouseover(@select_index <- this, i + 1)
@matches.unshift([@query, @query]) if @multiselect.options.enable_new_options
@select_index(0)
else
@matches: []
@container.css("display", "none")
@query: null
select_index: (index) ->
items: @list.find("li")
items.removeClass("auto-focus")
items.filter(":eq(${index})").addClass("auto-focus")
@current: index
navigate_down: ->
next: @current + 1
next: 0 if next >= @matches.length
@select_index(next)
navigate_up: ->
next: @current - 1
next: @matches.length - 1 if next < 0
@select_index(next)
create_item: (text, highlight) ->
item: $(document.createElement("li"))
item.click =>
@multiselect.add_and_reset()
@search()
@input.focus()
item.html(text)
@list.append(item)
item
val: ->
@matches[@current]
highlight: (text, highlight) ->
reg: "(${RegExp.escape(highlight)})"
text.replace(new RegExp(reg, "gi"), '<em>$1</em>')
matching_completions: (text) ->
reg: new RegExp(RegExp.escape(text), "i")
count: 0
$.grep @completions, (c) =>
return false if count >= @multiselect.options.max_complete_results
return false if $.inArray(c[1], @multiselect.values_real()) > -1
if c[0].match(reg)
count++
true
else
false
# Hook jQuery extension
$.fn.multiselect: (options) ->
options ?= {}
$(this).each ->
- new $.MultiSelect(this, options)
+ if this.tagName.toLowerCase() == "select"
+ input: $(document.createElement("input"))
+ input.attr("type", "text")
+ input.attr("name", this.name)
+ input.attr("id", this.id)
+
+ completions: []
+ for option in this.options
+ completions.push([option.innerHTML, option.value])
+
+ select_options: {
+ completions: completions
+ enable_new_options: false
+ }
+
+ $.extend(select_options, options)
+
+ $(this).replaceWith(input)
+
+ new $.MultiSelect(input, select_options)
+ else if this.tagName.toLowerCase() == "input" and this.type == "text"
+ new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '')
entitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
unentitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
blank: -> this.trim().length == 0
present: -> not @blank()
};
RegExp.escape: (str) ->
String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
wilkerlucio/jquery-multiselect
|
21b0517b81e88fe9c7312b0b543bd352db59750b
|
option to disable new options in input
|
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index 7775d2e..9295c60 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,516 +1,521 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
BACKSPACE: 8,
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ",",
completions: [],
- max_complete_results: 5
+ max_complete_results: 5,
+ enable_new_options: true
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
this.parse_value();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
return this.parse_value(1);
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
if (this.autocomplete.val()) {
e.preventDefault();
return this.add_and_reset();
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.observer.bind([KEY.BACKSPACE], (function(__this) {
var __func = function(e) {
var caret;
if (this.values.length <= 0) {
return null;
}
caret = this.selection.get_caret();
if (caret[0] === 0 && caret[1] === 0) {
e.preventDefault();
return this.remove(this.values[this.values.length - 1]);
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.prototype.values_real = function values_real() {
return $.map(this.values, function(v) {
return v[1];
});
};
$.MultiSelect.prototype.parse_value = function parse_value(min) {
var _a, _b, _c, value, values;
min = (typeof min !== "undefined" && min !== null) ? min : 0;
values = this.input.val().split(this.options.separator);
if (values.length > min) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.present()) {
this.add([value, value]);
}
}
this.input.val("");
return this.autocomplete.search();
}
};
$.MultiSelect.prototype.add_and_reset = function add_and_reset() {
if (this.autocomplete.val()) {
this.add(this.autocomplete.val());
this.input.val("");
return this.autocomplete.search();
}
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value[1], this.values_real()) > -1) {
return null;
}
if (value[0].blank()) {
return null;
}
value[1] = value[1].trim();
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
a.html(value[0].entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
return this.remove(a.data("value"));
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
console.log(this.values);
this.values = $.grep(this.values, function(v) {
return v[1] !== value[1];
});
this.container.find("a.bit-box").each(function() {
if ($(this).data("value")[1] === value[1]) {
return $(this).remove();
}
});
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values_real().join(this.options.separator));
};
// Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
// Selection Helper
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
var r;
// For IE
if (document.selection) {
r = document.selection.createRange().duplicate();
r.moveEnd('character', this.input.value.length);
if (r.text === '') {
return [this.input.value.length, this.input.value.length];
} else {
return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)];
// Others
}
} else {
return [this.input.selectionStart, this.input.selectionEnd];
}
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
// Resizable Input Helper
$.MultiSelect.ResizableInput = function ResizableInput(element) {
this.input = $(element);
this.create_measurer();
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
return this;
};
$.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
var measurer;
if ($("#__jquery_multiselect_measurer")[0] === undefined) {
measurer = $(document.createElement("div"));
measurer.attr("id", "__jquery_multiselect_measurer");
measurer.css({
position: "absolute",
left: "-1000px",
top: "-1000px"
});
$(document.body).append(measurer);
}
this.measurer = $("#__jquery_multiselect_measurer:first");
return this.measurer.css({
fontSize: this.input.css('font-size'),
fontFamily: this.input.css('font-family')
});
};
$.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
this.measurer.html(this.input.val().entitizeHTML() + 'MM');
return this.measurer.innerWidth();
};
$.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
return this.input.css("width", this.calculate_width() + "px");
};
// AutoComplete Helper
$.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) {
this.multiselect = multiselect;
this.input = this.multiselect.input;
this.completions = this.parse_completions(completions);
this.matches = [];
this.create_elements();
this.bind_events();
return this;
};
$.MultiSelect.AutoComplete.prototype.parse_completions = function parse_completions(completions) {
return $.map(completions, function(value) {
if (typeof value === "string") {
return [[value, value]];
} else if (value instanceof Array && value.length === 2) {
return [value];
} else if (value.value && value.caption) {
return [[value.caption, value.value]];
} else if (console) {
return console.error("Invalid option " + (value));
}
});
};
$.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() {
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect-autocomplete");
this.container.css("width", this.multiselect.container.outerWidth());
this.container.css("display", "none");
this.container.append(this.def);
this.list = $(document.createElement("ul"));
this.list.addClass("feed");
this.container.append(this.list);
return this.multiselect.container.after(this.container);
};
$.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() {
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.multiselect.observer.bind(KEY.UP, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_up();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.multiselect.observer.bind(KEY.DOWN, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_down();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.AutoComplete.prototype.search = function search() {
var _a, _b, def, i, item, option;
if (this.input.val().trim() === this.query) {
return null;
}
// dont do operation if query is same
this.query = this.input.val().trim();
this.list.html("");
// clear list
this.current = 0;
if (this.query.present()) {
this.container.css("display", "block");
this.matches = this.matching_completions(this.query);
- def = this.create_item("Add <em>" + this.query + "</em>");
- def.mouseover((function(func, obj, args) {
- return function() {
- return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
- };
- }(this.select_index, this, [0])));
+ if (this.multiselect.options.enable_new_options) {
+ def = this.create_item("Add <em>" + this.query + "</em>");
+ def.mouseover((function(func, obj, args) {
+ return function() {
+ return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
+ };
+ }(this.select_index, this, [0])));
+ }
_a = this.matches;
for (i = 0, _b = _a.length; i < _b; i++) {
option = _a[i];
item = this.create_item(this.highlight(option[0], this.query));
item.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [i + 1])));
}
- this.matches.unshift([this.query, this.query]);
+ if (this.multiselect.options.enable_new_options) {
+ this.matches.unshift([this.query, this.query]);
+ }
return this.select_index(0);
} else {
this.matches = [];
this.container.css("display", "none");
this.query = null;
return this.query;
}
};
$.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) {
var items;
items = this.list.find("li");
items.removeClass("auto-focus");
items.filter(":eq(" + (index) + ")").addClass("auto-focus");
this.current = index;
return this.current;
};
$.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() {
var next;
next = this.current + 1;
if (next >= this.matches.length) {
next = 0;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() {
var next;
next = this.current - 1;
if (next < 0) {
next = this.matches.length - 1;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) {
var item;
item = $(document.createElement("li"));
item.click((function(__this) {
var __func = function() {
this.multiselect.add_and_reset();
this.search();
return this.input.focus();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
item.html(text);
this.list.append(item);
return item;
};
$.MultiSelect.AutoComplete.prototype.val = function val() {
return this.matches[this.current];
};
$.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) {
var reg;
reg = "(" + (RegExp.escape(highlight)) + ")";
return text.replace(new RegExp(reg, "gi"), '<em>$1</em>');
};
$.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) {
var count, reg;
reg = new RegExp(RegExp.escape(text), "i");
count = 0;
return $.grep(this.completions, (function(__this) {
var __func = function(c) {
if (count >= this.multiselect.options.max_complete_results) {
return false;
}
if ($.inArray(c[1], this.multiselect.values_real()) > -1) {
return false;
}
if (c[0].match(reg)) {
count++;
return true;
} else {
return false;
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// Hook jQuery extension
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
trim: function trim() {
return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '');
},
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
blank: function blank() {
return this.trim().length === 0;
},
present: function present() {
return !this.blank();
}
});
RegExp.escape = function escape(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index a8f3da3..48fd9b0 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,358 +1,361 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
BACKSPACE: 8
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
- completions: [],
+ completions: []
max_complete_results: 5
+ enable_new_options: true
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
@parse_value()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection: new $.MultiSelect.Selection(@input)
@resizable: new $.MultiSelect.ResizableInput(@input)
@observer: new $.MultiSelect.InputObserver(@input)
@autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
@parse_value(1)
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
if @autocomplete.val()
e.preventDefault()
@add_and_reset()
@observer.bind [KEY.BACKSPACE], (e) =>
return if @values.length <= 0
caret = @selection.get_caret()
if caret[0] == 0 and caret[1] == 0
e.preventDefault()
@remove(@values[@values.length - 1])
values_real: ->
$.map @values, (v) -> v[1]
parse_value: (min) ->
min ?= 0
values: @input.val().split(@options.separator)
if values.length > min
for value in values
@add [value, value] if value.present()
@input.val("")
@autocomplete.search()
add_and_reset: ->
if @autocomplete.val()
@add(@autocomplete.val())
@input.val("")
@autocomplete.search()
# add new element
add: (value) ->
return if $.inArray(value[1], @values_real()) > -1
return if value[0].blank()
value[1] = value[1].trim()
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
a.html(value[0].entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
console.log @values
@values: $.grep @values, (v) -> v[1] != value[1]
@container.find("a.bit-box").each ->
$(this).remove() if $(this).data("value")[1] == value[1]
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values_real().join(@options.separator))
# Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
# Selection Helper
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
# For IE
if document.selection
r: document.selection.createRange().duplicate()
r.moveEnd('character', @input.value.length)
if r.text == ''
[@input.value.length, @input.value.length]
else
[@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)]
# Others
else
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart: begin
@input.selectionEnd: end
set_caret_at_end: ->
@set_caret(@input.value.length)
# Resizable Input Helper
class $.MultiSelect.ResizableInput
constructor: (element) ->
@input: $(element)
@create_measurer()
@input.keypress(@set_width <- this)
@input.keyup(@set_width <- this)
@input.change(@set_width <- this)
create_measurer: ->
if $("#__jquery_multiselect_measurer")[0] == undefined
measurer: $(document.createElement("div"))
measurer.attr("id", "__jquery_multiselect_measurer")
measurer.css {
position: "absolute"
left: "-1000px"
top: "-1000px"
}
$(document.body).append(measurer)
@measurer: $("#__jquery_multiselect_measurer:first")
@measurer.css {
fontSize: @input.css('font-size')
fontFamily: @input.css('font-family')
}
calculate_width: ->
@measurer.html(@input.val().entitizeHTML() + 'MM')
@measurer.innerWidth()
set_width: ->
@input.css("width", @calculate_width() + "px")
# AutoComplete Helper
class $.MultiSelect.AutoComplete
constructor: (multiselect, completions) ->
@multiselect: multiselect
@input: @multiselect.input
@completions: @parse_completions(completions)
@matches: []
@create_elements()
@bind_events()
parse_completions: (completions) ->
$.map completions, (value) ->
if typeof value == "string"
[[value, value]]
else if value instanceof Array and value.length == 2
[value]
else if value.value and value.caption
[[value.caption, value.value]]
else
console.error "Invalid option ${value}" if console
create_elements: ->
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect-autocomplete")
@container.css("width", @multiselect.container.outerWidth())
@container.css("display", "none")
@container.append(@def)
@list: $(document.createElement("ul"))
@list.addClass("feed")
@container.append(@list)
@multiselect.container.after(@container)
bind_events: ->
@input.keypress(@search <- this)
@input.keyup(@search <- this)
@input.change(@search <- this)
@multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up()
@multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down()
search: ->
return if @input.val().trim() == @query # dont do operation if query is same
@query: @input.val().trim()
@list.html("") # clear list
@current: 0
if @query.present()
@container.css("display", "block")
@matches: @matching_completions(@query)
- def: @create_item("Add <em>" + @query + "</em>")
- def.mouseover(@select_index <- this, 0)
+ if @multiselect.options.enable_new_options
+ def: @create_item("Add <em>" + @query + "</em>")
+ def.mouseover(@select_index <- this, 0)
for option, i in @matches
item: @create_item(@highlight(option[0], @query))
item.mouseover(@select_index <- this, i + 1)
- @matches.unshift([@query, @query])
+ @matches.unshift([@query, @query]) if @multiselect.options.enable_new_options
+
@select_index(0)
else
@matches: []
@container.css("display", "none")
@query: null
select_index: (index) ->
items: @list.find("li")
items.removeClass("auto-focus")
items.filter(":eq(${index})").addClass("auto-focus")
@current: index
navigate_down: ->
next: @current + 1
next: 0 if next >= @matches.length
@select_index(next)
navigate_up: ->
next: @current - 1
next: @matches.length - 1 if next < 0
@select_index(next)
create_item: (text, highlight) ->
item: $(document.createElement("li"))
item.click =>
@multiselect.add_and_reset()
@search()
@input.focus()
item.html(text)
@list.append(item)
item
val: ->
@matches[@current]
highlight: (text, highlight) ->
reg: "(${RegExp.escape(highlight)})"
text.replace(new RegExp(reg, "gi"), '<em>$1</em>')
matching_completions: (text) ->
reg: new RegExp(RegExp.escape(text), "i")
count: 0
$.grep @completions, (c) =>
return false if count >= @multiselect.options.max_complete_results
return false if $.inArray(c[1], @multiselect.values_real()) > -1
if c[0].match(reg)
count++
true
else
false
# Hook jQuery extension
$.fn.multiselect: (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '')
entitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
unentitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
blank: -> this.trim().length == 0
present: -> not @blank()
};
RegExp.escape: (str) ->
String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
wilkerlucio/jquery-multiselect
|
6a3529416a9d88d3bb4dca02f94241b4c604b169
|
support completion of values different from captions
|
diff --git a/examples/index.html b/examples/index.html
index c706a96..3e602a3 100644
--- a/examples/index.html
+++ b/examples/index.html
@@ -1,42 +1,42 @@
<!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" xml:lang="en">
<head>
<title>JqueryMultiSelect Example</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="../css/jquery.multiselect.css" media="all">
<script type="text/javascript" src="../vendor/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../js/jquery.multiselect.js"></script>
<script type="text/javascript">
names = [
"Alejandra Pizarnik",
- "Alicia Partnoy",
- "Andres Rivera",
+ ["Alicia Partnoy", "alicia"],
+ {caption: "Andres Rivera", value: "andres"},
"Antonio Porchia",
"Arturo Andres Roig",
"Felipe Pigna",
"Gustavo Nielsen",
"Hector German Oesterheld",
"Juan Carlos Portantiero",
"Juan L. Ortiz",
"Manuel Mujica Lainez",
"Manuel Puig",
"Mario Rodriguez Cobos",
"Olga Orozco",
"Osvaldo Tierra",
"Ricardo Piglia",
"Ricardo Rojas",
"Roberto Payro",
"Silvina Ocampo",
"Victoria Ocampo",
"Zuriel Barron"
]
$(function() {
$("#sample-tags").multiselect({completions: names});
});
</script>
</head>
<body>
<input type="text" name="tags" id="sample-tags" value="initial,values" />
</body>
</html>
\ No newline at end of file
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index 1f55575..7775d2e 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,497 +1,516 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
BACKSPACE: 8,
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ",",
completions: [],
max_complete_results: 5
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
this.parse_value();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
return this.parse_value(1);
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
if (this.autocomplete.val()) {
e.preventDefault();
return this.add_and_reset();
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.observer.bind([KEY.BACKSPACE], (function(__this) {
var __func = function(e) {
var caret;
if (this.values.length <= 0) {
return null;
}
caret = this.selection.get_caret();
if (caret[0] === 0 && caret[1] === 0) {
e.preventDefault();
return this.remove(this.values[this.values.length - 1]);
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
+ $.MultiSelect.prototype.values_real = function values_real() {
+ return $.map(this.values, function(v) {
+ return v[1];
+ });
+ };
$.MultiSelect.prototype.parse_value = function parse_value(min) {
var _a, _b, _c, value, values;
min = (typeof min !== "undefined" && min !== null) ? min : 0;
values = this.input.val().split(this.options.separator);
if (values.length > min) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.present()) {
- this.add(value);
+ this.add([value, value]);
}
}
this.input.val("");
return this.autocomplete.search();
}
};
$.MultiSelect.prototype.add_and_reset = function add_and_reset() {
if (this.autocomplete.val()) {
this.add(this.autocomplete.val());
this.input.val("");
return this.autocomplete.search();
}
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
- if ($.inArray(value, this.values) > -1) {
+ if ($.inArray(value[1], this.values_real()) > -1) {
return null;
}
- if (value.blank()) {
+ if (value[0].blank()) {
return null;
}
- value = value.trim();
+ value[1] = value[1].trim();
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
- a.html(value.entitizeHTML());
+ a.html(value[0].entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
return this.remove(a.data("value"));
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
+ console.log(this.values);
this.values = $.grep(this.values, function(v) {
- return v !== value;
+ return v[1] !== value[1];
});
this.container.find("a.bit-box").each(function() {
- if ($(this).data("value") === value) {
+ if ($(this).data("value")[1] === value[1]) {
return $(this).remove();
}
});
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
- return this.hidden.val(this.values.join(this.options.separator));
+ return this.hidden.val(this.values_real().join(this.options.separator));
};
// Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
// Selection Helper
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
var r;
// For IE
if (document.selection) {
r = document.selection.createRange().duplicate();
r.moveEnd('character', this.input.value.length);
if (r.text === '') {
return [this.input.value.length, this.input.value.length];
} else {
return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)];
// Others
}
} else {
return [this.input.selectionStart, this.input.selectionEnd];
}
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
// Resizable Input Helper
$.MultiSelect.ResizableInput = function ResizableInput(element) {
this.input = $(element);
this.create_measurer();
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
return this;
};
$.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
var measurer;
if ($("#__jquery_multiselect_measurer")[0] === undefined) {
measurer = $(document.createElement("div"));
measurer.attr("id", "__jquery_multiselect_measurer");
measurer.css({
position: "absolute",
left: "-1000px",
top: "-1000px"
});
$(document.body).append(measurer);
}
this.measurer = $("#__jquery_multiselect_measurer:first");
return this.measurer.css({
fontSize: this.input.css('font-size'),
fontFamily: this.input.css('font-family')
});
};
$.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
this.measurer.html(this.input.val().entitizeHTML() + 'MM');
return this.measurer.innerWidth();
};
$.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
return this.input.css("width", this.calculate_width() + "px");
};
// AutoComplete Helper
$.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) {
this.multiselect = multiselect;
this.input = this.multiselect.input;
- this.completions = completions;
+ this.completions = this.parse_completions(completions);
this.matches = [];
this.create_elements();
this.bind_events();
return this;
};
+ $.MultiSelect.AutoComplete.prototype.parse_completions = function parse_completions(completions) {
+ return $.map(completions, function(value) {
+ if (typeof value === "string") {
+ return [[value, value]];
+ } else if (value instanceof Array && value.length === 2) {
+ return [value];
+ } else if (value.value && value.caption) {
+ return [[value.caption, value.value]];
+ } else if (console) {
+ return console.error("Invalid option " + (value));
+ }
+ });
+ };
$.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() {
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect-autocomplete");
this.container.css("width", this.multiselect.container.outerWidth());
this.container.css("display", "none");
this.container.append(this.def);
this.list = $(document.createElement("ul"));
this.list.addClass("feed");
this.container.append(this.list);
return this.multiselect.container.after(this.container);
};
$.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() {
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.multiselect.observer.bind(KEY.UP, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_up();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.multiselect.observer.bind(KEY.DOWN, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_down();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.AutoComplete.prototype.search = function search() {
var _a, _b, def, i, item, option;
if (this.input.val().trim() === this.query) {
return null;
}
// dont do operation if query is same
this.query = this.input.val().trim();
this.list.html("");
// clear list
this.current = 0;
if (this.query.present()) {
this.container.css("display", "block");
this.matches = this.matching_completions(this.query);
def = this.create_item("Add <em>" + this.query + "</em>");
def.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [0])));
_a = this.matches;
for (i = 0, _b = _a.length; i < _b; i++) {
option = _a[i];
- item = this.create_item(this.highlight(option, this.query));
+ item = this.create_item(this.highlight(option[0], this.query));
item.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [i + 1])));
}
- this.matches.unshift(this.query);
+ this.matches.unshift([this.query, this.query]);
return this.select_index(0);
} else {
this.matches = [];
this.container.css("display", "none");
this.query = null;
return this.query;
}
};
$.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) {
var items;
items = this.list.find("li");
items.removeClass("auto-focus");
items.filter(":eq(" + (index) + ")").addClass("auto-focus");
this.current = index;
return this.current;
};
$.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() {
var next;
next = this.current + 1;
if (next >= this.matches.length) {
next = 0;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() {
var next;
next = this.current - 1;
if (next < 0) {
next = this.matches.length - 1;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) {
var item;
item = $(document.createElement("li"));
item.click((function(__this) {
var __func = function() {
this.multiselect.add_and_reset();
this.search();
return this.input.focus();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
item.html(text);
this.list.append(item);
return item;
};
$.MultiSelect.AutoComplete.prototype.val = function val() {
return this.matches[this.current];
};
$.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) {
var reg;
reg = "(" + (RegExp.escape(highlight)) + ")";
return text.replace(new RegExp(reg, "gi"), '<em>$1</em>');
};
$.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) {
var count, reg;
reg = new RegExp(RegExp.escape(text), "i");
count = 0;
return $.grep(this.completions, (function(__this) {
var __func = function(c) {
if (count >= this.multiselect.options.max_complete_results) {
return false;
}
- if ($.inArray(c, this.multiselect.values) > -1) {
+ if ($.inArray(c[1], this.multiselect.values_real()) > -1) {
return false;
}
- if (c.match(reg)) {
+ if (c[0].match(reg)) {
count++;
return true;
} else {
return false;
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// Hook jQuery extension
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
trim: function trim() {
return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '');
},
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
blank: function blank() {
return this.trim().length === 0;
},
present: function present() {
return !this.blank();
}
});
RegExp.escape = function escape(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index 47cf4bb..a8f3da3 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,343 +1,358 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
BACKSPACE: 8
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
completions: [],
max_complete_results: 5
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
@parse_value()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection: new $.MultiSelect.Selection(@input)
@resizable: new $.MultiSelect.ResizableInput(@input)
@observer: new $.MultiSelect.InputObserver(@input)
@autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
@parse_value(1)
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
if @autocomplete.val()
e.preventDefault()
@add_and_reset()
@observer.bind [KEY.BACKSPACE], (e) =>
return if @values.length <= 0
caret = @selection.get_caret()
if caret[0] == 0 and caret[1] == 0
e.preventDefault()
@remove(@values[@values.length - 1])
+ values_real: ->
+ $.map @values, (v) -> v[1]
+
parse_value: (min) ->
min ?= 0
values: @input.val().split(@options.separator)
if values.length > min
for value in values
- @add value if value.present()
+ @add [value, value] if value.present()
@input.val("")
@autocomplete.search()
add_and_reset: ->
if @autocomplete.val()
@add(@autocomplete.val())
@input.val("")
@autocomplete.search()
# add new element
add: (value) ->
- return if $.inArray(value, @values) > -1
- return if value.blank()
+ return if $.inArray(value[1], @values_real()) > -1
+ return if value[0].blank()
- value = value.trim()
+ value[1] = value[1].trim()
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
- a.html(value.entitizeHTML())
+ a.html(value[0].entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
- @values: $.grep @values, (v) -> v != value
+ console.log @values
+ @values: $.grep @values, (v) -> v[1] != value[1]
@container.find("a.bit-box").each ->
- $(this).remove() if $(this).data("value") == value
+ $(this).remove() if $(this).data("value")[1] == value[1]
@refresh_hidden()
refresh_hidden: ->
- @hidden.val(@values.join(@options.separator))
+ @hidden.val(@values_real().join(@options.separator))
# Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
# Selection Helper
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
# For IE
if document.selection
r: document.selection.createRange().duplicate()
r.moveEnd('character', @input.value.length)
if r.text == ''
[@input.value.length, @input.value.length]
else
[@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)]
# Others
else
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart: begin
@input.selectionEnd: end
set_caret_at_end: ->
@set_caret(@input.value.length)
# Resizable Input Helper
class $.MultiSelect.ResizableInput
constructor: (element) ->
@input: $(element)
@create_measurer()
@input.keypress(@set_width <- this)
@input.keyup(@set_width <- this)
@input.change(@set_width <- this)
create_measurer: ->
if $("#__jquery_multiselect_measurer")[0] == undefined
measurer: $(document.createElement("div"))
measurer.attr("id", "__jquery_multiselect_measurer")
measurer.css {
position: "absolute"
left: "-1000px"
top: "-1000px"
}
$(document.body).append(measurer)
@measurer: $("#__jquery_multiselect_measurer:first")
@measurer.css {
fontSize: @input.css('font-size')
fontFamily: @input.css('font-family')
}
calculate_width: ->
@measurer.html(@input.val().entitizeHTML() + 'MM')
@measurer.innerWidth()
set_width: ->
@input.css("width", @calculate_width() + "px")
# AutoComplete Helper
class $.MultiSelect.AutoComplete
constructor: (multiselect, completions) ->
@multiselect: multiselect
@input: @multiselect.input
- @completions: completions
+ @completions: @parse_completions(completions)
@matches: []
@create_elements()
@bind_events()
+ parse_completions: (completions) ->
+ $.map completions, (value) ->
+ if typeof value == "string"
+ [[value, value]]
+ else if value instanceof Array and value.length == 2
+ [value]
+ else if value.value and value.caption
+ [[value.caption, value.value]]
+ else
+ console.error "Invalid option ${value}" if console
+
create_elements: ->
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect-autocomplete")
@container.css("width", @multiselect.container.outerWidth())
@container.css("display", "none")
@container.append(@def)
@list: $(document.createElement("ul"))
@list.addClass("feed")
@container.append(@list)
@multiselect.container.after(@container)
bind_events: ->
@input.keypress(@search <- this)
@input.keyup(@search <- this)
@input.change(@search <- this)
@multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up()
@multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down()
search: ->
return if @input.val().trim() == @query # dont do operation if query is same
@query: @input.val().trim()
@list.html("") # clear list
@current: 0
if @query.present()
@container.css("display", "block")
@matches: @matching_completions(@query)
def: @create_item("Add <em>" + @query + "</em>")
def.mouseover(@select_index <- this, 0)
for option, i in @matches
- item: @create_item(@highlight(option, @query))
+ item: @create_item(@highlight(option[0], @query))
item.mouseover(@select_index <- this, i + 1)
- @matches.unshift(@query)
+ @matches.unshift([@query, @query])
@select_index(0)
else
@matches: []
@container.css("display", "none")
@query: null
select_index: (index) ->
items: @list.find("li")
items.removeClass("auto-focus")
items.filter(":eq(${index})").addClass("auto-focus")
@current: index
navigate_down: ->
next: @current + 1
next: 0 if next >= @matches.length
@select_index(next)
navigate_up: ->
next: @current - 1
next: @matches.length - 1 if next < 0
@select_index(next)
create_item: (text, highlight) ->
item: $(document.createElement("li"))
item.click =>
@multiselect.add_and_reset()
@search()
@input.focus()
item.html(text)
@list.append(item)
item
val: ->
@matches[@current]
highlight: (text, highlight) ->
reg: "(${RegExp.escape(highlight)})"
text.replace(new RegExp(reg, "gi"), '<em>$1</em>')
matching_completions: (text) ->
reg: new RegExp(RegExp.escape(text), "i")
count: 0
$.grep @completions, (c) =>
return false if count >= @multiselect.options.max_complete_results
- return false if $.inArray(c, @multiselect.values) > -1
+ return false if $.inArray(c[1], @multiselect.values_real()) > -1
- if c.match(reg)
+ if c[0].match(reg)
count++
true
else
false
# Hook jQuery extension
$.fn.multiselect: (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '')
entitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
unentitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
blank: -> this.trim().length == 0
present: -> not @blank()
};
RegExp.escape: (str) ->
String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
wilkerlucio/jquery-multiselect
|
aa8207a96d14ac897f3e31c60cdff62ee71f943b
|
build 0.1.2
|
diff --git a/VERSION b/VERSION
index 6da28dd..8294c18 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.1.1
\ No newline at end of file
+0.1.2
\ No newline at end of file
diff --git a/dist/jquery.multiselect.0.1.2.min.js b/dist/jquery.multiselect.0.1.2.min.js
new file mode 100644
index 0000000..3648846
--- /dev/null
+++ b/dist/jquery.multiselect.0.1.2.min.js
@@ -0,0 +1,30 @@
+/**
+ * Copyright (c) 2010 Wilker Lúcio
+ *
+ * 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.
+ */
+
+(function($){var KEY;KEY={BACKSPACE:8,TAB:9,RETURN:13,ESCAPE:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,COLON:188,DOT:190};$.MultiSelect=function MultiSelect(element,options){this.options={separator:",",completions:[],max_complete_results:5};$.extend(this.options,options||{});this.values=[];this.input=$(element);this.initialize_elements();this.initialize_events();this.parse_value();return this;};$.MultiSelect.prototype.initialize_elements=function initialize_elements(){this.hidden=$(document.createElement("input"));this.hidden.attr("name",this.input.attr("name"));this.hidden.attr("type","hidden");this.input.removeAttr("name");this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect");this.input_wrapper=$(document.createElement("a"));this.input_wrapper.addClass("bit-input");this.input.replaceWith(this.container);this.container.append(this.input_wrapper);this.input_wrapper.append(this.input);return this.container.before(this.hidden);};$.MultiSelect.prototype.initialize_events=function initialize_events(){this.selection=new $.MultiSelect.Selection(this.input);this.resizable=new $.MultiSelect.ResizableInput(this.input);this.observer=new $.MultiSelect.InputObserver(this.input);this.autocomplete=new $.MultiSelect.AutoComplete(this,this.options.completions);this.input.click((function(__this){var __func=function(e){return e.stopPropagation();};return(function(){return __func.apply(__this,arguments);});})(this));this.input.keyup((function(__this){var __func=function(){return this.parse_value(1);};return(function(){return __func.apply(__this,arguments);});})(this));this.container.click((function(__this){var __func=function(){this.input.focus();return this.selection.set_caret_at_end();};return(function(){return __func.apply(__this,arguments);});})(this));this.observer.bind([KEY.TAB,KEY.RETURN],(function(__this){var __func=function(e){if(this.autocomplete.val()){e.preventDefault();return this.add_and_reset();}};return(function(){return __func.apply(__this,arguments);});})(this));return this.observer.bind([KEY.BACKSPACE],(function(__this){var __func=function(e){var caret;if(this.values.length<=0){return null;}
+caret=this.selection.get_caret();if(caret[0]===0&&caret[1]===0){e.preventDefault();return this.remove(this.values[this.values.length-1]);}};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.prototype.parse_value=function parse_value(min){var _a,_b,_c,value,values;min=(typeof min!=="undefined"&&min!==null)?min:0;values=this.input.val().split(this.options.separator);if(values.length>min){_b=values;for(_a=0,_c=_b.length;_a<_c;_a++){value=_b[_a];if(value.present()){this.add(value);}}
+this.input.val("");return this.autocomplete.search();}};$.MultiSelect.prototype.add_and_reset=function add_and_reset(){if(this.autocomplete.val()){this.add(this.autocomplete.val());this.input.val("");return this.autocomplete.search();}};$.MultiSelect.prototype.add=function add(value){var a,close;if($.inArray(value,this.values)>-1){return null;}
+if(value.blank()){return null;}
+value=value.trim();this.values.push(value);a=$(document.createElement("a"));a.addClass("bit bit-box");a.mouseover(function(){return $(this).addClass("bit-hover");});a.mouseout(function(){return $(this).removeClass("bit-hover");});a.data("value",value);a.html(value.entitizeHTML());close=$(document.createElement("a"));close.addClass("closebutton");close.click((function(__this){var __func=function(){return this.remove(a.data("value"));};return(function(){return __func.apply(__this,arguments);});})(this));a.append(close);this.input_wrapper.before(a);return this.refresh_hidden();};$.MultiSelect.prototype.remove=function remove(value){this.values=$.grep(this.values,function(v){return v!==value;});this.container.find("a.bit-box").each(function(){if($(this).data("value")===value){return $(this).remove();}});return this.refresh_hidden();};$.MultiSelect.prototype.refresh_hidden=function refresh_hidden(){return this.hidden.val(this.values.join(this.options.separator));};$.MultiSelect.InputObserver=function InputObserver(element){this.input=$(element);this.input.keydown((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.handle_keydown,this,[])));this.events=[];return this;};$.MultiSelect.InputObserver.prototype.bind=function bind(key,callback){return this.events.push([key,callback]);};$.MultiSelect.InputObserver.prototype.handle_keydown=function handle_keydown(e){var _a,_b,_c,_d,_e,callback,event,keys;_a=[];_c=this.events;for(_b=0,_d=_c.length;_b<_d;_b++){event=_c[_b];_a.push((function(){_e=event;keys=_e[0];callback=_e[1];if(!(keys.push)){keys=[keys];}
+if($.inArray(e.keyCode,keys)>-1){return callback(e);}}).call(this));}
+return _a;};$.MultiSelect.Selection=function Selection(element){this.input=$(element)[0];return this;};$.MultiSelect.Selection.prototype.get_caret=function get_caret(){var r;if(document.selection){r=document.selection.createRange().duplicate();r.moveEnd('character',this.input.value.length);if(r.text===''){return[this.input.value.length,this.input.value.length];}else{return[this.input.value.lastIndexOf(r.text),this.input.value.lastIndexOf(r.text)];}}else{return[this.input.selectionStart,this.input.selectionEnd];}};$.MultiSelect.Selection.prototype.set_caret=function set_caret(begin,end){end=(typeof end!=="undefined"&&end!==null)?end:begin;this.input.selectionStart=begin;this.input.selectionEnd=end;return this.input.selectionEnd;};$.MultiSelect.Selection.prototype.set_caret_at_end=function set_caret_at_end(){return this.set_caret(this.input.value.length);};$.MultiSelect.ResizableInput=function ResizableInput(element){this.input=$(element);this.create_measurer();this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));return this;};$.MultiSelect.ResizableInput.prototype.create_measurer=function create_measurer(){var measurer;if($("#__jquery_multiselect_measurer")[0]===undefined){measurer=$(document.createElement("div"));measurer.attr("id","__jquery_multiselect_measurer");measurer.css({position:"absolute",left:"-1000px",top:"-1000px"});$(document.body).append(measurer);}
+this.measurer=$("#__jquery_multiselect_measurer:first");return this.measurer.css({fontSize:this.input.css('font-size'),fontFamily:this.input.css('font-family')});};$.MultiSelect.ResizableInput.prototype.calculate_width=function calculate_width(){this.measurer.html(this.input.val().entitizeHTML()+'MM');return this.measurer.innerWidth();};$.MultiSelect.ResizableInput.prototype.set_width=function set_width(){return this.input.css("width",this.calculate_width()+"px");};$.MultiSelect.AutoComplete=function AutoComplete(multiselect,completions){this.multiselect=multiselect;this.input=this.multiselect.input;this.completions=completions;this.matches=[];this.create_elements();this.bind_events();return this;};$.MultiSelect.AutoComplete.prototype.create_elements=function create_elements(){this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect-autocomplete");this.container.css("width",this.multiselect.container.outerWidth());this.container.css("display","none");this.container.append(this.def);this.list=$(document.createElement("ul"));this.list.addClass("feed");this.container.append(this.list);return this.multiselect.container.after(this.container);};$.MultiSelect.AutoComplete.prototype.bind_events=function bind_events(){this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.multiselect.observer.bind(KEY.UP,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_up();};return(function(){return __func.apply(__this,arguments);});})(this));return this.multiselect.observer.bind(KEY.DOWN,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_down();};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.AutoComplete.prototype.search=function search(){var _a,_b,def,i,item,option;if(this.input.val().trim()===this.query){return null;}
+this.query=this.input.val().trim();this.list.html("");this.current=0;if(this.query.present()){this.container.css("display","block");this.matches=this.matching_completions(this.query);def=this.create_item("Add <em>"+this.query+"</em>");def.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[0])));_a=this.matches;for(i=0,_b=_a.length;i<_b;i++){option=_a[i];item=this.create_item(this.highlight(option,this.query));item.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[i+1])));}
+this.matches.unshift(this.query);return this.select_index(0);}else{this.matches=[];this.container.css("display","none");this.query=null;return this.query;}};$.MultiSelect.AutoComplete.prototype.select_index=function select_index(index){var items;items=this.list.find("li");items.removeClass("auto-focus");items.filter(":eq("+(index)+")").addClass("auto-focus");this.current=index;return this.current;};$.MultiSelect.AutoComplete.prototype.navigate_down=function navigate_down(){var next;next=this.current+1;if(next>=this.matches.length){next=0;}
+return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.navigate_up=function navigate_up(){var next;next=this.current-1;if(next<0){next=this.matches.length-1;}
+return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.create_item=function create_item(text,highlight){var item;item=$(document.createElement("li"));item.click((function(__this){var __func=function(){this.multiselect.add_and_reset();this.search();return this.input.focus();};return(function(){return __func.apply(__this,arguments);});})(this));item.html(text);this.list.append(item);return item;};$.MultiSelect.AutoComplete.prototype.val=function val(){return this.matches[this.current];};$.MultiSelect.AutoComplete.prototype.highlight=function highlight(text,highlight){var reg;reg="("+(RegExp.escape(highlight))+")";return text.replace(new RegExp(reg,"gi"),'<em>$1</em>');};$.MultiSelect.AutoComplete.prototype.matching_completions=function matching_completions(text){var count,reg;reg=new RegExp(RegExp.escape(text),"i");count=0;return $.grep(this.completions,(function(__this){var __func=function(c){if(count>=this.multiselect.options.max_complete_results){return false;}
+if($.inArray(c,this.multiselect.values)>-1){return false;}
+if(c.match(reg)){count++;return true;}else{return false;}};return(function(){return __func.apply(__this,arguments);});})(this));};$.fn.multiselect=function multiselect(options){options=(typeof options!=="undefined"&&options!==null)?options:{};return $(this).each(function(){return new $.MultiSelect(this,options);});};return $.fn.multiselect;})(jQuery);$.extend(String.prototype,{trim:function trim(){return this.replace(/^[\r\n\s]/g,'').replace(/[\r\n\s]$/g,'');},entitizeHTML:function entitizeHTML(){return this.replace(/</g,'<').replace(/>/g,'>');},unentitizeHTML:function unentitizeHTML(){return this.replace(/</g,'<').replace(/>/g,'>');},blank:function blank(){return this.trim().length===0;},present:function present(){return!this.blank();}});RegExp.escape=function escape(str){return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g,'\\$1');};
\ No newline at end of file
|
wilkerlucio/jquery-multiselect
|
a722b5239cd134821f855ced5420d5c3e2292ac3
|
fix tab again
|
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index 9fbfdd2..1f55575 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,495 +1,497 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
BACKSPACE: 8,
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ",",
completions: [],
max_complete_results: 5
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
this.parse_value();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
return this.parse_value(1);
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
if (this.autocomplete.val()) {
e.preventDefault();
return this.add_and_reset();
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.observer.bind([KEY.BACKSPACE], (function(__this) {
var __func = function(e) {
var caret;
if (this.values.length <= 0) {
return null;
}
caret = this.selection.get_caret();
if (caret[0] === 0 && caret[1] === 0) {
e.preventDefault();
return this.remove(this.values[this.values.length - 1]);
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.prototype.parse_value = function parse_value(min) {
var _a, _b, _c, value, values;
min = (typeof min !== "undefined" && min !== null) ? min : 0;
values = this.input.val().split(this.options.separator);
if (values.length > min) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.present()) {
this.add(value);
}
}
this.input.val("");
return this.autocomplete.search();
}
};
$.MultiSelect.prototype.add_and_reset = function add_and_reset() {
if (this.autocomplete.val()) {
this.add(this.autocomplete.val());
- return this.input.val("");
+ this.input.val("");
+ return this.autocomplete.search();
}
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value, this.values) > -1) {
return null;
}
if (value.blank()) {
return null;
}
value = value.trim();
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
a.html(value.entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
return this.remove(a.data("value"));
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
this.values = $.grep(this.values, function(v) {
return v !== value;
});
this.container.find("a.bit-box").each(function() {
if ($(this).data("value") === value) {
return $(this).remove();
}
});
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values.join(this.options.separator));
};
// Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
// Selection Helper
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
var r;
// For IE
if (document.selection) {
r = document.selection.createRange().duplicate();
r.moveEnd('character', this.input.value.length);
if (r.text === '') {
return [this.input.value.length, this.input.value.length];
} else {
return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)];
// Others
}
} else {
return [this.input.selectionStart, this.input.selectionEnd];
}
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
// Resizable Input Helper
$.MultiSelect.ResizableInput = function ResizableInput(element) {
this.input = $(element);
this.create_measurer();
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
return this;
};
$.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
var measurer;
if ($("#__jquery_multiselect_measurer")[0] === undefined) {
measurer = $(document.createElement("div"));
measurer.attr("id", "__jquery_multiselect_measurer");
measurer.css({
position: "absolute",
left: "-1000px",
top: "-1000px"
});
$(document.body).append(measurer);
}
this.measurer = $("#__jquery_multiselect_measurer:first");
return this.measurer.css({
fontSize: this.input.css('font-size'),
fontFamily: this.input.css('font-family')
});
};
$.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
this.measurer.html(this.input.val().entitizeHTML() + 'MM');
return this.measurer.innerWidth();
};
$.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
return this.input.css("width", this.calculate_width() + "px");
};
// AutoComplete Helper
$.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) {
this.multiselect = multiselect;
this.input = this.multiselect.input;
this.completions = completions;
this.matches = [];
this.create_elements();
this.bind_events();
return this;
};
$.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() {
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect-autocomplete");
this.container.css("width", this.multiselect.container.outerWidth());
this.container.css("display", "none");
this.container.append(this.def);
this.list = $(document.createElement("ul"));
this.list.addClass("feed");
this.container.append(this.list);
return this.multiselect.container.after(this.container);
};
$.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() {
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.multiselect.observer.bind(KEY.UP, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_up();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.multiselect.observer.bind(KEY.DOWN, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_down();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.AutoComplete.prototype.search = function search() {
var _a, _b, def, i, item, option;
if (this.input.val().trim() === this.query) {
return null;
}
// dont do operation if query is same
this.query = this.input.val().trim();
this.list.html("");
// clear list
this.current = 0;
if (this.query.present()) {
this.container.css("display", "block");
this.matches = this.matching_completions(this.query);
def = this.create_item("Add <em>" + this.query + "</em>");
def.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [0])));
_a = this.matches;
for (i = 0, _b = _a.length; i < _b; i++) {
option = _a[i];
item = this.create_item(this.highlight(option, this.query));
item.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [i + 1])));
}
this.matches.unshift(this.query);
return this.select_index(0);
} else {
+ this.matches = [];
this.container.css("display", "none");
this.query = null;
return this.query;
}
};
$.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) {
var items;
items = this.list.find("li");
items.removeClass("auto-focus");
items.filter(":eq(" + (index) + ")").addClass("auto-focus");
this.current = index;
return this.current;
};
$.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() {
var next;
next = this.current + 1;
if (next >= this.matches.length) {
next = 0;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() {
var next;
next = this.current - 1;
if (next < 0) {
next = this.matches.length - 1;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) {
var item;
item = $(document.createElement("li"));
item.click((function(__this) {
var __func = function() {
this.multiselect.add_and_reset();
this.search();
return this.input.focus();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
item.html(text);
this.list.append(item);
return item;
};
$.MultiSelect.AutoComplete.prototype.val = function val() {
return this.matches[this.current];
};
$.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) {
var reg;
reg = "(" + (RegExp.escape(highlight)) + ")";
return text.replace(new RegExp(reg, "gi"), '<em>$1</em>');
};
$.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) {
var count, reg;
reg = new RegExp(RegExp.escape(text), "i");
count = 0;
return $.grep(this.completions, (function(__this) {
var __func = function(c) {
if (count >= this.multiselect.options.max_complete_results) {
return false;
}
if ($.inArray(c, this.multiselect.values) > -1) {
return false;
}
if (c.match(reg)) {
count++;
return true;
} else {
return false;
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// Hook jQuery extension
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
trim: function trim() {
return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '');
},
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
blank: function blank() {
return this.trim().length === 0;
},
present: function present() {
return !this.blank();
}
});
RegExp.escape = function escape(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index 29dc3be..47cf4bb 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,341 +1,343 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
BACKSPACE: 8
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
completions: [],
max_complete_results: 5
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
@parse_value()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection: new $.MultiSelect.Selection(@input)
@resizable: new $.MultiSelect.ResizableInput(@input)
@observer: new $.MultiSelect.InputObserver(@input)
@autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
@parse_value(1)
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
if @autocomplete.val()
e.preventDefault()
@add_and_reset()
@observer.bind [KEY.BACKSPACE], (e) =>
return if @values.length <= 0
caret = @selection.get_caret()
if caret[0] == 0 and caret[1] == 0
e.preventDefault()
@remove(@values[@values.length - 1])
parse_value: (min) ->
min ?= 0
values: @input.val().split(@options.separator)
if values.length > min
for value in values
@add value if value.present()
@input.val("")
@autocomplete.search()
add_and_reset: ->
if @autocomplete.val()
@add(@autocomplete.val())
@input.val("")
+ @autocomplete.search()
# add new element
add: (value) ->
return if $.inArray(value, @values) > -1
return if value.blank()
value = value.trim()
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
a.html(value.entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
@values: $.grep @values, (v) -> v != value
@container.find("a.bit-box").each ->
$(this).remove() if $(this).data("value") == value
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values.join(@options.separator))
# Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
# Selection Helper
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
# For IE
if document.selection
r: document.selection.createRange().duplicate()
r.moveEnd('character', @input.value.length)
if r.text == ''
[@input.value.length, @input.value.length]
else
[@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)]
# Others
else
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart: begin
@input.selectionEnd: end
set_caret_at_end: ->
@set_caret(@input.value.length)
# Resizable Input Helper
class $.MultiSelect.ResizableInput
constructor: (element) ->
@input: $(element)
@create_measurer()
@input.keypress(@set_width <- this)
@input.keyup(@set_width <- this)
@input.change(@set_width <- this)
create_measurer: ->
if $("#__jquery_multiselect_measurer")[0] == undefined
measurer: $(document.createElement("div"))
measurer.attr("id", "__jquery_multiselect_measurer")
measurer.css {
position: "absolute"
left: "-1000px"
top: "-1000px"
}
$(document.body).append(measurer)
@measurer: $("#__jquery_multiselect_measurer:first")
@measurer.css {
fontSize: @input.css('font-size')
fontFamily: @input.css('font-family')
}
calculate_width: ->
@measurer.html(@input.val().entitizeHTML() + 'MM')
@measurer.innerWidth()
set_width: ->
@input.css("width", @calculate_width() + "px")
# AutoComplete Helper
class $.MultiSelect.AutoComplete
constructor: (multiselect, completions) ->
@multiselect: multiselect
@input: @multiselect.input
@completions: completions
@matches: []
@create_elements()
@bind_events()
create_elements: ->
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect-autocomplete")
@container.css("width", @multiselect.container.outerWidth())
@container.css("display", "none")
@container.append(@def)
@list: $(document.createElement("ul"))
@list.addClass("feed")
@container.append(@list)
@multiselect.container.after(@container)
bind_events: ->
@input.keypress(@search <- this)
@input.keyup(@search <- this)
@input.change(@search <- this)
@multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up()
@multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down()
search: ->
return if @input.val().trim() == @query # dont do operation if query is same
@query: @input.val().trim()
@list.html("") # clear list
@current: 0
if @query.present()
@container.css("display", "block")
@matches: @matching_completions(@query)
def: @create_item("Add <em>" + @query + "</em>")
def.mouseover(@select_index <- this, 0)
for option, i in @matches
item: @create_item(@highlight(option, @query))
item.mouseover(@select_index <- this, i + 1)
@matches.unshift(@query)
@select_index(0)
else
+ @matches: []
@container.css("display", "none")
@query: null
select_index: (index) ->
items: @list.find("li")
items.removeClass("auto-focus")
items.filter(":eq(${index})").addClass("auto-focus")
@current: index
navigate_down: ->
next: @current + 1
next: 0 if next >= @matches.length
@select_index(next)
navigate_up: ->
next: @current - 1
next: @matches.length - 1 if next < 0
@select_index(next)
create_item: (text, highlight) ->
item: $(document.createElement("li"))
item.click =>
@multiselect.add_and_reset()
@search()
@input.focus()
item.html(text)
@list.append(item)
item
val: ->
@matches[@current]
highlight: (text, highlight) ->
reg: "(${RegExp.escape(highlight)})"
text.replace(new RegExp(reg, "gi"), '<em>$1</em>')
matching_completions: (text) ->
reg: new RegExp(RegExp.escape(text), "i")
count: 0
$.grep @completions, (c) =>
return false if count >= @multiselect.options.max_complete_results
return false if $.inArray(c, @multiselect.values) > -1
if c.match(reg)
count++
true
else
false
# Hook jQuery extension
$.fn.multiselect: (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '')
entitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
unentitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
blank: -> this.trim().length == 0
present: -> not @blank()
};
RegExp.escape: (str) ->
String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
wilkerlucio/jquery-multiselect
|
bdf0f4575b43499bfdfe47c5194b7da44452dcfe
|
release 0.1.1
|
diff --git a/VERSION b/VERSION
index 6c6aa7c..6da28dd 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.1.0
\ No newline at end of file
+0.1.1
\ No newline at end of file
diff --git a/dist/jquery.multiselect.0.1.1.min.js b/dist/jquery.multiselect.0.1.1.min.js
new file mode 100644
index 0000000..41eccc4
--- /dev/null
+++ b/dist/jquery.multiselect.0.1.1.min.js
@@ -0,0 +1,30 @@
+/**
+ * Copyright (c) 2010 Wilker Lúcio
+ *
+ * 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.
+ */
+
+(function($){var KEY;KEY={BACKSPACE:8,TAB:9,RETURN:13,ESCAPE:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,COLON:188,DOT:190};$.MultiSelect=function MultiSelect(element,options){this.options={separator:",",completions:[],max_complete_results:5};$.extend(this.options,options||{});this.values=[];this.input=$(element);this.initialize_elements();this.initialize_events();this.parse_value();return this;};$.MultiSelect.prototype.initialize_elements=function initialize_elements(){this.hidden=$(document.createElement("input"));this.hidden.attr("name",this.input.attr("name"));this.hidden.attr("type","hidden");this.input.removeAttr("name");this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect");this.input_wrapper=$(document.createElement("a"));this.input_wrapper.addClass("bit-input");this.input.replaceWith(this.container);this.container.append(this.input_wrapper);this.input_wrapper.append(this.input);return this.container.before(this.hidden);};$.MultiSelect.prototype.initialize_events=function initialize_events(){this.selection=new $.MultiSelect.Selection(this.input);this.resizable=new $.MultiSelect.ResizableInput(this.input);this.observer=new $.MultiSelect.InputObserver(this.input);this.autocomplete=new $.MultiSelect.AutoComplete(this,this.options.completions);this.input.click((function(__this){var __func=function(e){return e.stopPropagation();};return(function(){return __func.apply(__this,arguments);});})(this));this.input.keyup((function(__this){var __func=function(){return this.parse_value(1);};return(function(){return __func.apply(__this,arguments);});})(this));this.container.click((function(__this){var __func=function(){this.input.focus();return this.selection.set_caret_at_end();};return(function(){return __func.apply(__this,arguments);});})(this));this.observer.bind([KEY.TAB,KEY.RETURN],(function(__this){var __func=function(e){if(this.autocomplete.val()){e.preventDefault();return this.add_and_reset();}};return(function(){return __func.apply(__this,arguments);});})(this));return this.observer.bind([KEY.BACKSPACE],(function(__this){var __func=function(e){var caret;if(this.values.length<=0){return null;}
+caret=this.selection.get_caret();if(caret[0]===0&&caret[1]===0){e.preventDefault();return this.remove(this.values[this.values.length-1]);}};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.prototype.parse_value=function parse_value(min){var _a,_b,_c,value,values;min=(typeof min!=="undefined"&&min!==null)?min:0;values=this.input.val().split(this.options.separator);if(values.length>min){_b=values;for(_a=0,_c=_b.length;_a<_c;_a++){value=_b[_a];if(value.present()){this.add(value);}}
+this.input.val("");return this.autocomplete.search();}};$.MultiSelect.prototype.add_and_reset=function add_and_reset(){if(this.autocomplete.val()){this.add(this.autocomplete.val());return this.input.val("");}};$.MultiSelect.prototype.add=function add(value){var a,close;if($.inArray(value,this.values)>-1){return null;}
+if(value.blank()){return null;}
+value=value.trim();this.values.push(value);a=$(document.createElement("a"));a.addClass("bit bit-box");a.mouseover(function(){return $(this).addClass("bit-hover");});a.mouseout(function(){return $(this).removeClass("bit-hover");});a.data("value",value);a.html(value.entitizeHTML());close=$(document.createElement("a"));close.addClass("closebutton");close.click((function(__this){var __func=function(){return this.remove(a.data("value"));};return(function(){return __func.apply(__this,arguments);});})(this));a.append(close);this.input_wrapper.before(a);return this.refresh_hidden();};$.MultiSelect.prototype.remove=function remove(value){this.values=$.grep(this.values,function(v){return v!==value;});this.container.find("a.bit-box").each(function(){if($(this).data("value")===value){return $(this).remove();}});return this.refresh_hidden();};$.MultiSelect.prototype.refresh_hidden=function refresh_hidden(){return this.hidden.val(this.values.join(this.options.separator));};$.MultiSelect.InputObserver=function InputObserver(element){this.input=$(element);this.input.keydown((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.handle_keydown,this,[])));this.events=[];return this;};$.MultiSelect.InputObserver.prototype.bind=function bind(key,callback){return this.events.push([key,callback]);};$.MultiSelect.InputObserver.prototype.handle_keydown=function handle_keydown(e){var _a,_b,_c,_d,_e,callback,event,keys;_a=[];_c=this.events;for(_b=0,_d=_c.length;_b<_d;_b++){event=_c[_b];_a.push((function(){_e=event;keys=_e[0];callback=_e[1];if(!(keys.push)){keys=[keys];}
+if($.inArray(e.keyCode,keys)>-1){return callback(e);}}).call(this));}
+return _a;};$.MultiSelect.Selection=function Selection(element){this.input=$(element)[0];return this;};$.MultiSelect.Selection.prototype.get_caret=function get_caret(){var r;if(document.selection){r=document.selection.createRange().duplicate();r.moveEnd('character',this.input.value.length);if(r.text===''){return[this.input.value.length,this.input.value.length];}else{return[this.input.value.lastIndexOf(r.text),this.input.value.lastIndexOf(r.text)];}}else{return[this.input.selectionStart,this.input.selectionEnd];}};$.MultiSelect.Selection.prototype.set_caret=function set_caret(begin,end){end=(typeof end!=="undefined"&&end!==null)?end:begin;this.input.selectionStart=begin;this.input.selectionEnd=end;return this.input.selectionEnd;};$.MultiSelect.Selection.prototype.set_caret_at_end=function set_caret_at_end(){return this.set_caret(this.input.value.length);};$.MultiSelect.ResizableInput=function ResizableInput(element){this.input=$(element);this.create_measurer();this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));return this;};$.MultiSelect.ResizableInput.prototype.create_measurer=function create_measurer(){var measurer;if($("#__jquery_multiselect_measurer")[0]===undefined){measurer=$(document.createElement("div"));measurer.attr("id","__jquery_multiselect_measurer");measurer.css({position:"absolute",left:"-1000px",top:"-1000px"});$(document.body).append(measurer);}
+this.measurer=$("#__jquery_multiselect_measurer:first");return this.measurer.css({fontSize:this.input.css('font-size'),fontFamily:this.input.css('font-family')});};$.MultiSelect.ResizableInput.prototype.calculate_width=function calculate_width(){this.measurer.html(this.input.val().entitizeHTML()+'MM');return this.measurer.innerWidth();};$.MultiSelect.ResizableInput.prototype.set_width=function set_width(){return this.input.css("width",this.calculate_width()+"px");};$.MultiSelect.AutoComplete=function AutoComplete(multiselect,completions){this.multiselect=multiselect;this.input=this.multiselect.input;this.completions=completions;this.matches=[];this.create_elements();this.bind_events();return this;};$.MultiSelect.AutoComplete.prototype.create_elements=function create_elements(){this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect-autocomplete");this.container.css("width",this.multiselect.container.outerWidth());this.container.css("display","none");this.container.append(this.def);this.list=$(document.createElement("ul"));this.list.addClass("feed");this.container.append(this.list);return this.multiselect.container.after(this.container);};$.MultiSelect.AutoComplete.prototype.bind_events=function bind_events(){this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.multiselect.observer.bind(KEY.UP,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_up();};return(function(){return __func.apply(__this,arguments);});})(this));return this.multiselect.observer.bind(KEY.DOWN,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_down();};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.AutoComplete.prototype.search=function search(){var _a,_b,def,i,item,option;if(this.input.val().trim()===this.query){return null;}
+this.query=this.input.val().trim();this.list.html("");this.current=0;if(this.query.present()){this.container.css("display","block");this.matches=this.matching_completions(this.query);def=this.create_item("Add <em>"+this.query+"</em>");def.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[0])));_a=this.matches;for(i=0,_b=_a.length;i<_b;i++){option=_a[i];item=this.create_item(this.highlight(option,this.query));item.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[i+1])));}
+this.matches.unshift(this.query);return this.select_index(0);}else{this.container.css("display","none");this.query=null;return this.query;}};$.MultiSelect.AutoComplete.prototype.select_index=function select_index(index){var items;items=this.list.find("li");items.removeClass("auto-focus");items.filter(":eq("+(index)+")").addClass("auto-focus");this.current=index;return this.current;};$.MultiSelect.AutoComplete.prototype.navigate_down=function navigate_down(){var next;next=this.current+1;if(next>=this.matches.length){next=0;}
+return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.navigate_up=function navigate_up(){var next;next=this.current-1;if(next<0){next=this.matches.length-1;}
+return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.create_item=function create_item(text,highlight){var item;item=$(document.createElement("li"));item.click((function(__this){var __func=function(){this.multiselect.add_and_reset();this.search();return this.input.focus();};return(function(){return __func.apply(__this,arguments);});})(this));item.html(text);this.list.append(item);return item;};$.MultiSelect.AutoComplete.prototype.val=function val(){return this.matches[this.current];};$.MultiSelect.AutoComplete.prototype.highlight=function highlight(text,highlight){var reg;reg="("+(RegExp.escape(highlight))+")";return text.replace(new RegExp(reg,"gi"),'<em>$1</em>');};$.MultiSelect.AutoComplete.prototype.matching_completions=function matching_completions(text){var count,reg;reg=new RegExp(RegExp.escape(text),"i");count=0;return $.grep(this.completions,(function(__this){var __func=function(c){if(count>=this.multiselect.options.max_complete_results){return false;}
+if($.inArray(c,this.multiselect.values)>-1){return false;}
+if(c.match(reg)){count++;return true;}else{return false;}};return(function(){return __func.apply(__this,arguments);});})(this));};$.fn.multiselect=function multiselect(options){options=(typeof options!=="undefined"&&options!==null)?options:{};return $(this).each(function(){return new $.MultiSelect(this,options);});};return $.fn.multiselect;})(jQuery);$.extend(String.prototype,{trim:function trim(){return this.replace(/^[\r\n\s]/g,'').replace(/[\r\n\s]$/g,'');},entitizeHTML:function entitizeHTML(){return this.replace(/</g,'<').replace(/>/g,'>');},unentitizeHTML:function unentitizeHTML(){return this.replace(/</g,'<').replace(/>/g,'>');},blank:function blank(){return this.trim().length===0;},present:function present(){return!this.blank();}});RegExp.escape=function escape(str){return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g,'\\$1');};
\ No newline at end of file
|
wilkerlucio/jquery-multiselect
|
a8162d1034bac3f00897a8dcd0f8e202afbf4dbe
|
only prevent default on return and tab if has value
|
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index edf8d30..9fbfdd2 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,493 +1,495 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
BACKSPACE: 8,
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ",",
completions: [],
max_complete_results: 5
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
this.parse_value();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
return this.parse_value(1);
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
- e.preventDefault();
- return this.add_and_reset();
+ if (this.autocomplete.val()) {
+ e.preventDefault();
+ return this.add_and_reset();
+ }
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.observer.bind([KEY.BACKSPACE], (function(__this) {
var __func = function(e) {
var caret;
if (this.values.length <= 0) {
return null;
}
caret = this.selection.get_caret();
if (caret[0] === 0 && caret[1] === 0) {
e.preventDefault();
return this.remove(this.values[this.values.length - 1]);
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.prototype.parse_value = function parse_value(min) {
var _a, _b, _c, value, values;
min = (typeof min !== "undefined" && min !== null) ? min : 0;
values = this.input.val().split(this.options.separator);
if (values.length > min) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.present()) {
this.add(value);
}
}
this.input.val("");
return this.autocomplete.search();
}
};
$.MultiSelect.prototype.add_and_reset = function add_and_reset() {
if (this.autocomplete.val()) {
this.add(this.autocomplete.val());
return this.input.val("");
}
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value, this.values) > -1) {
return null;
}
if (value.blank()) {
return null;
}
value = value.trim();
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
a.html(value.entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
return this.remove(a.data("value"));
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
this.values = $.grep(this.values, function(v) {
return v !== value;
});
this.container.find("a.bit-box").each(function() {
if ($(this).data("value") === value) {
return $(this).remove();
}
});
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values.join(this.options.separator));
};
// Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
// Selection Helper
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
var r;
// For IE
if (document.selection) {
r = document.selection.createRange().duplicate();
r.moveEnd('character', this.input.value.length);
if (r.text === '') {
return [this.input.value.length, this.input.value.length];
} else {
return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)];
// Others
}
} else {
return [this.input.selectionStart, this.input.selectionEnd];
}
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
// Resizable Input Helper
$.MultiSelect.ResizableInput = function ResizableInput(element) {
this.input = $(element);
this.create_measurer();
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
return this;
};
$.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
var measurer;
if ($("#__jquery_multiselect_measurer")[0] === undefined) {
measurer = $(document.createElement("div"));
measurer.attr("id", "__jquery_multiselect_measurer");
measurer.css({
position: "absolute",
left: "-1000px",
top: "-1000px"
});
$(document.body).append(measurer);
}
this.measurer = $("#__jquery_multiselect_measurer:first");
return this.measurer.css({
fontSize: this.input.css('font-size'),
fontFamily: this.input.css('font-family')
});
};
$.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
this.measurer.html(this.input.val().entitizeHTML() + 'MM');
return this.measurer.innerWidth();
};
$.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
return this.input.css("width", this.calculate_width() + "px");
};
// AutoComplete Helper
$.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) {
this.multiselect = multiselect;
this.input = this.multiselect.input;
this.completions = completions;
this.matches = [];
this.create_elements();
this.bind_events();
return this;
};
$.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() {
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect-autocomplete");
this.container.css("width", this.multiselect.container.outerWidth());
this.container.css("display", "none");
this.container.append(this.def);
this.list = $(document.createElement("ul"));
this.list.addClass("feed");
this.container.append(this.list);
return this.multiselect.container.after(this.container);
};
$.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() {
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.multiselect.observer.bind(KEY.UP, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_up();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.multiselect.observer.bind(KEY.DOWN, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_down();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.AutoComplete.prototype.search = function search() {
var _a, _b, def, i, item, option;
if (this.input.val().trim() === this.query) {
return null;
}
// dont do operation if query is same
this.query = this.input.val().trim();
this.list.html("");
// clear list
this.current = 0;
if (this.query.present()) {
this.container.css("display", "block");
this.matches = this.matching_completions(this.query);
def = this.create_item("Add <em>" + this.query + "</em>");
def.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [0])));
_a = this.matches;
for (i = 0, _b = _a.length; i < _b; i++) {
option = _a[i];
item = this.create_item(this.highlight(option, this.query));
item.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [i + 1])));
}
this.matches.unshift(this.query);
return this.select_index(0);
} else {
this.container.css("display", "none");
this.query = null;
return this.query;
}
};
$.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) {
var items;
items = this.list.find("li");
items.removeClass("auto-focus");
items.filter(":eq(" + (index) + ")").addClass("auto-focus");
this.current = index;
return this.current;
};
$.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() {
var next;
next = this.current + 1;
if (next >= this.matches.length) {
next = 0;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() {
var next;
next = this.current - 1;
if (next < 0) {
next = this.matches.length - 1;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) {
var item;
item = $(document.createElement("li"));
item.click((function(__this) {
var __func = function() {
this.multiselect.add_and_reset();
this.search();
return this.input.focus();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
item.html(text);
this.list.append(item);
return item;
};
$.MultiSelect.AutoComplete.prototype.val = function val() {
return this.matches[this.current];
};
$.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) {
var reg;
reg = "(" + (RegExp.escape(highlight)) + ")";
return text.replace(new RegExp(reg, "gi"), '<em>$1</em>');
};
$.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) {
var count, reg;
reg = new RegExp(RegExp.escape(text), "i");
count = 0;
return $.grep(this.completions, (function(__this) {
var __func = function(c) {
if (count >= this.multiselect.options.max_complete_results) {
return false;
}
if ($.inArray(c, this.multiselect.values) > -1) {
return false;
}
if (c.match(reg)) {
count++;
return true;
} else {
return false;
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// Hook jQuery extension
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
trim: function trim() {
return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '');
},
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
blank: function blank() {
return this.trim().length === 0;
},
present: function present() {
return !this.blank();
}
});
RegExp.escape = function escape(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index 956ffd7..29dc3be 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,340 +1,341 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
BACKSPACE: 8
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
completions: [],
max_complete_results: 5
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
@parse_value()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection: new $.MultiSelect.Selection(@input)
@resizable: new $.MultiSelect.ResizableInput(@input)
@observer: new $.MultiSelect.InputObserver(@input)
@autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
@parse_value(1)
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
- e.preventDefault()
- @add_and_reset()
+ if @autocomplete.val()
+ e.preventDefault()
+ @add_and_reset()
@observer.bind [KEY.BACKSPACE], (e) =>
return if @values.length <= 0
caret = @selection.get_caret()
if caret[0] == 0 and caret[1] == 0
e.preventDefault()
@remove(@values[@values.length - 1])
parse_value: (min) ->
min ?= 0
values: @input.val().split(@options.separator)
if values.length > min
for value in values
@add value if value.present()
@input.val("")
@autocomplete.search()
add_and_reset: ->
if @autocomplete.val()
@add(@autocomplete.val())
@input.val("")
# add new element
add: (value) ->
return if $.inArray(value, @values) > -1
return if value.blank()
value = value.trim()
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
a.html(value.entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
@values: $.grep @values, (v) -> v != value
@container.find("a.bit-box").each ->
$(this).remove() if $(this).data("value") == value
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values.join(@options.separator))
# Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
# Selection Helper
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
# For IE
if document.selection
r: document.selection.createRange().duplicate()
r.moveEnd('character', @input.value.length)
if r.text == ''
[@input.value.length, @input.value.length]
else
[@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)]
# Others
else
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart: begin
@input.selectionEnd: end
set_caret_at_end: ->
@set_caret(@input.value.length)
# Resizable Input Helper
class $.MultiSelect.ResizableInput
constructor: (element) ->
@input: $(element)
@create_measurer()
@input.keypress(@set_width <- this)
@input.keyup(@set_width <- this)
@input.change(@set_width <- this)
create_measurer: ->
if $("#__jquery_multiselect_measurer")[0] == undefined
measurer: $(document.createElement("div"))
measurer.attr("id", "__jquery_multiselect_measurer")
measurer.css {
position: "absolute"
left: "-1000px"
top: "-1000px"
}
$(document.body).append(measurer)
@measurer: $("#__jquery_multiselect_measurer:first")
@measurer.css {
fontSize: @input.css('font-size')
fontFamily: @input.css('font-family')
}
calculate_width: ->
@measurer.html(@input.val().entitizeHTML() + 'MM')
@measurer.innerWidth()
set_width: ->
@input.css("width", @calculate_width() + "px")
# AutoComplete Helper
class $.MultiSelect.AutoComplete
constructor: (multiselect, completions) ->
@multiselect: multiselect
@input: @multiselect.input
@completions: completions
@matches: []
@create_elements()
@bind_events()
create_elements: ->
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect-autocomplete")
@container.css("width", @multiselect.container.outerWidth())
@container.css("display", "none")
@container.append(@def)
@list: $(document.createElement("ul"))
@list.addClass("feed")
@container.append(@list)
@multiselect.container.after(@container)
bind_events: ->
@input.keypress(@search <- this)
@input.keyup(@search <- this)
@input.change(@search <- this)
@multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up()
@multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down()
search: ->
return if @input.val().trim() == @query # dont do operation if query is same
@query: @input.val().trim()
@list.html("") # clear list
@current: 0
if @query.present()
@container.css("display", "block")
@matches: @matching_completions(@query)
def: @create_item("Add <em>" + @query + "</em>")
def.mouseover(@select_index <- this, 0)
for option, i in @matches
item: @create_item(@highlight(option, @query))
item.mouseover(@select_index <- this, i + 1)
@matches.unshift(@query)
@select_index(0)
else
@container.css("display", "none")
@query: null
select_index: (index) ->
items: @list.find("li")
items.removeClass("auto-focus")
items.filter(":eq(${index})").addClass("auto-focus")
@current: index
navigate_down: ->
next: @current + 1
next: 0 if next >= @matches.length
@select_index(next)
navigate_up: ->
next: @current - 1
next: @matches.length - 1 if next < 0
@select_index(next)
create_item: (text, highlight) ->
item: $(document.createElement("li"))
item.click =>
@multiselect.add_and_reset()
@search()
@input.focus()
item.html(text)
@list.append(item)
item
val: ->
@matches[@current]
highlight: (text, highlight) ->
reg: "(${RegExp.escape(highlight)})"
text.replace(new RegExp(reg, "gi"), '<em>$1</em>')
matching_completions: (text) ->
reg: new RegExp(RegExp.escape(text), "i")
count: 0
$.grep @completions, (c) =>
return false if count >= @multiselect.options.max_complete_results
return false if $.inArray(c, @multiselect.values) > -1
if c.match(reg)
count++
true
else
false
# Hook jQuery extension
$.fn.multiselect: (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '')
entitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
unentitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
blank: -> this.trim().length == 0
present: -> not @blank()
};
RegExp.escape: (str) ->
String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
wilkerlucio/jquery-multiselect
|
c2e810ff8e3be058334ce0007408bf6c70f6a245
|
added build task and minified version
|
diff --git a/.gitignore b/.gitignore
index e43b0f9..2a7b1d7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
.DS_Store
+.bundle
diff --git a/Gemfile b/Gemfile
new file mode 100644
index 0000000..948d226
--- /dev/null
+++ b/Gemfile
@@ -0,0 +1,3 @@
+source :gemcutter
+
+gem 'jsmin'
\ No newline at end of file
diff --git a/Rakefile b/Rakefile
index 20f3ae9..8bd2e17 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,8 +1,44 @@
+require 'rubygems'
+require 'bundler'
+
+Bundler.setup
+Bundler.require
+
desc "Compile CoffeeScripts and watch for changes"
task :coffee do
coffee = IO.popen 'coffee -wc --no-wrap src/*.coffee -o js 2>&1'
while line = coffee.gets
puts line
end
+end
+
+desc "Build minified version"
+task :build do
+ content = File.read("js/jquery.multiselect.js")
+ minyfied = JSMin.minify(content)
+ version = File.read("VERSION")
+
+ licence = <<LIC
+/**
+ * Copyright (c) 2010 Wilker Lúcio
+ *
+ * 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.
+ */
+LIC
+
+ File.open("dist/jquery.multiselect.#{version}.min.js", "wb") do |f|
+ f << licence
+ f << minyfied
+ end
end
\ No newline at end of file
diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000..6c6aa7c
--- /dev/null
+++ b/VERSION
@@ -0,0 +1 @@
+0.1.0
\ No newline at end of file
diff --git a/dist/jquery.multiselect.0.1.0.min.js b/dist/jquery.multiselect.0.1.0.min.js
new file mode 100644
index 0000000..ac389ed
--- /dev/null
+++ b/dist/jquery.multiselect.0.1.0.min.js
@@ -0,0 +1,30 @@
+/**
+ * Copyright (c) 2010 Wilker Lúcio
+ *
+ * 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.
+ */
+
+(function($){var KEY;KEY={BACKSPACE:8,TAB:9,RETURN:13,ESCAPE:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,COLON:188,DOT:190};$.MultiSelect=function MultiSelect(element,options){this.options={separator:",",completions:[],max_complete_results:5};$.extend(this.options,options||{});this.values=[];this.input=$(element);this.initialize_elements();this.initialize_events();this.parse_value();return this;};$.MultiSelect.prototype.initialize_elements=function initialize_elements(){this.hidden=$(document.createElement("input"));this.hidden.attr("name",this.input.attr("name"));this.hidden.attr("type","hidden");this.input.removeAttr("name");this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect");this.input_wrapper=$(document.createElement("a"));this.input_wrapper.addClass("bit-input");this.input.replaceWith(this.container);this.container.append(this.input_wrapper);this.input_wrapper.append(this.input);return this.container.before(this.hidden);};$.MultiSelect.prototype.initialize_events=function initialize_events(){this.selection=new $.MultiSelect.Selection(this.input);this.resizable=new $.MultiSelect.ResizableInput(this.input);this.observer=new $.MultiSelect.InputObserver(this.input);this.autocomplete=new $.MultiSelect.AutoComplete(this,this.options.completions);this.input.click((function(__this){var __func=function(e){return e.stopPropagation();};return(function(){return __func.apply(__this,arguments);});})(this));this.input.keyup((function(__this){var __func=function(){return this.parse_value(1);};return(function(){return __func.apply(__this,arguments);});})(this));this.container.click((function(__this){var __func=function(){this.input.focus();return this.selection.set_caret_at_end();};return(function(){return __func.apply(__this,arguments);});})(this));this.observer.bind([KEY.TAB,KEY.RETURN],(function(__this){var __func=function(e){e.preventDefault();return this.add_and_reset();};return(function(){return __func.apply(__this,arguments);});})(this));return this.observer.bind([KEY.BACKSPACE],(function(__this){var __func=function(e){var caret;if(this.values.length<=0){return null;}
+caret=this.selection.get_caret();if(caret[0]===0&&caret[1]===0){e.preventDefault();return this.remove(this.values[this.values.length-1]);}};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.prototype.parse_value=function parse_value(min){var _a,_b,_c,value,values;min=(typeof min!=="undefined"&&min!==null)?min:0;values=this.input.val().split(this.options.separator);if(values.length>min){_b=values;for(_a=0,_c=_b.length;_a<_c;_a++){value=_b[_a];if(value.present()){this.add(value);}}
+this.input.val("");return this.autocomplete.search();}};$.MultiSelect.prototype.add_and_reset=function add_and_reset(){if(this.autocomplete.val()){this.add(this.autocomplete.val());return this.input.val("");}};$.MultiSelect.prototype.add=function add(value){var a,close;if($.inArray(value,this.values)>-1){return null;}
+if(value.blank()){return null;}
+value=value.trim();this.values.push(value);a=$(document.createElement("a"));a.addClass("bit bit-box");a.mouseover(function(){return $(this).addClass("bit-hover");});a.mouseout(function(){return $(this).removeClass("bit-hover");});a.data("value",value);a.html(value.entitizeHTML());close=$(document.createElement("a"));close.addClass("closebutton");close.click((function(__this){var __func=function(){return this.remove(a.data("value"));};return(function(){return __func.apply(__this,arguments);});})(this));a.append(close);this.input_wrapper.before(a);return this.refresh_hidden();};$.MultiSelect.prototype.remove=function remove(value){this.values=$.grep(this.values,function(v){return v!==value;});this.container.find("a.bit-box").each(function(){if($(this).data("value")===value){return $(this).remove();}});return this.refresh_hidden();};$.MultiSelect.prototype.refresh_hidden=function refresh_hidden(){return this.hidden.val(this.values.join(this.options.separator));};$.MultiSelect.InputObserver=function InputObserver(element){this.input=$(element);this.input.keydown((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.handle_keydown,this,[])));this.events=[];return this;};$.MultiSelect.InputObserver.prototype.bind=function bind(key,callback){return this.events.push([key,callback]);};$.MultiSelect.InputObserver.prototype.handle_keydown=function handle_keydown(e){var _a,_b,_c,_d,_e,callback,event,keys;_a=[];_c=this.events;for(_b=0,_d=_c.length;_b<_d;_b++){event=_c[_b];_a.push((function(){_e=event;keys=_e[0];callback=_e[1];if(!(keys.push)){keys=[keys];}
+if($.inArray(e.keyCode,keys)>-1){return callback(e);}}).call(this));}
+return _a;};$.MultiSelect.Selection=function Selection(element){this.input=$(element)[0];return this;};$.MultiSelect.Selection.prototype.get_caret=function get_caret(){var r;if(document.selection){r=document.selection.createRange().duplicate();r.moveEnd('character',this.input.value.length);if(r.text===''){return[this.input.value.length,this.input.value.length];}else{return[this.input.value.lastIndexOf(r.text),this.input.value.lastIndexOf(r.text)];}}else{return[this.input.selectionStart,this.input.selectionEnd];}};$.MultiSelect.Selection.prototype.set_caret=function set_caret(begin,end){end=(typeof end!=="undefined"&&end!==null)?end:begin;this.input.selectionStart=begin;this.input.selectionEnd=end;return this.input.selectionEnd;};$.MultiSelect.Selection.prototype.set_caret_at_end=function set_caret_at_end(){return this.set_caret(this.input.value.length);};$.MultiSelect.ResizableInput=function ResizableInput(element){this.input=$(element);this.create_measurer();this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.set_width,this,[])));return this;};$.MultiSelect.ResizableInput.prototype.create_measurer=function create_measurer(){var measurer;if($("#__jquery_multiselect_measurer")[0]===undefined){measurer=$(document.createElement("div"));measurer.attr("id","__jquery_multiselect_measurer");measurer.css({position:"absolute",left:"-1000px",top:"-1000px"});$(document.body).append(measurer);}
+this.measurer=$("#__jquery_multiselect_measurer:first");return this.measurer.css({fontSize:this.input.css('font-size'),fontFamily:this.input.css('font-family')});};$.MultiSelect.ResizableInput.prototype.calculate_width=function calculate_width(){this.measurer.html(this.input.val().entitizeHTML()+'MM');return this.measurer.innerWidth();};$.MultiSelect.ResizableInput.prototype.set_width=function set_width(){return this.input.css("width",this.calculate_width()+"px");};$.MultiSelect.AutoComplete=function AutoComplete(multiselect,completions){this.multiselect=multiselect;this.input=this.multiselect.input;this.completions=completions;this.matches=[];this.create_elements();this.bind_events();return this;};$.MultiSelect.AutoComplete.prototype.create_elements=function create_elements(){this.container=$(document.createElement("div"));this.container.addClass("jquery-multiselect-autocomplete");this.container.css("width",this.multiselect.container.outerWidth());this.container.css("display","none");this.container.append(this.def);this.list=$(document.createElement("ul"));this.list.addClass("feed");this.container.append(this.list);return this.multiselect.container.after(this.container);};$.MultiSelect.AutoComplete.prototype.bind_events=function bind_events(){this.input.keypress((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.keyup((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.input.change((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.search,this,[])));this.multiselect.observer.bind(KEY.UP,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_up();};return(function(){return __func.apply(__this,arguments);});})(this));return this.multiselect.observer.bind(KEY.DOWN,(function(__this){var __func=function(e){e.preventDefault();return this.navigate_down();};return(function(){return __func.apply(__this,arguments);});})(this));};$.MultiSelect.AutoComplete.prototype.search=function search(){var _a,_b,def,i,item,option;if(this.input.val().trim()===this.query){return null;}
+this.query=this.input.val().trim();this.list.html("");this.current=0;if(this.query.present()){this.container.css("display","block");this.matches=this.matching_completions(this.query);def=this.create_item("Add <em>"+this.query+"</em>");def.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[0])));_a=this.matches;for(i=0,_b=_a.length;i<_b;i++){option=_a[i];item=this.create_item(this.highlight(option,this.query));item.mouseover((function(func,obj,args){return function(){return func.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)));};}(this.select_index,this,[i+1])));}
+this.matches.unshift(this.query);return this.select_index(0);}else{this.container.css("display","none");this.query=null;return this.query;}};$.MultiSelect.AutoComplete.prototype.select_index=function select_index(index){var items;items=this.list.find("li");items.removeClass("auto-focus");items.filter(":eq("+(index)+")").addClass("auto-focus");this.current=index;return this.current;};$.MultiSelect.AutoComplete.prototype.navigate_down=function navigate_down(){var next;next=this.current+1;if(next>=this.matches.length){next=0;}
+return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.navigate_up=function navigate_up(){var next;next=this.current-1;if(next<0){next=this.matches.length-1;}
+return this.select_index(next);};$.MultiSelect.AutoComplete.prototype.create_item=function create_item(text,highlight){var item;item=$(document.createElement("li"));item.click((function(__this){var __func=function(){this.multiselect.add_and_reset();this.search();return this.input.focus();};return(function(){return __func.apply(__this,arguments);});})(this));item.html(text);this.list.append(item);return item;};$.MultiSelect.AutoComplete.prototype.val=function val(){return this.matches[this.current];};$.MultiSelect.AutoComplete.prototype.highlight=function highlight(text,highlight){var reg;reg="("+(RegExp.escape(highlight))+")";return text.replace(new RegExp(reg,"gi"),'<em>$1</em>');};$.MultiSelect.AutoComplete.prototype.matching_completions=function matching_completions(text){var count,reg;reg=new RegExp(RegExp.escape(text),"i");count=0;return $.grep(this.completions,(function(__this){var __func=function(c){if(count>=this.multiselect.options.max_complete_results){return false;}
+if($.inArray(c,this.multiselect.values)>-1){return false;}
+if(c.match(reg)){count++;return true;}else{return false;}};return(function(){return __func.apply(__this,arguments);});})(this));};$.fn.multiselect=function multiselect(options){options=(typeof options!=="undefined"&&options!==null)?options:{};return $(this).each(function(){return new $.MultiSelect(this,options);});};return $.fn.multiselect;})(jQuery);$.extend(String.prototype,{trim:function trim(){return this.replace(/^[\r\n\s]/g,'').replace(/[\r\n\s]$/g,'');},entitizeHTML:function entitizeHTML(){return this.replace(/</g,'<').replace(/>/g,'>');},unentitizeHTML:function unentitizeHTML(){return this.replace(/</g,'<').replace(/>/g,'>');},blank:function blank(){return this.trim().length===0;},present:function present(){return!this.blank();}});RegExp.escape=function escape(str){return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g,'\\$1');};
\ No newline at end of file
|
wilkerlucio/jquery-multiselect
|
609045a5eeffc38c2d0c8e69b93c829840388854
|
Added README content
|
diff --git a/README.textile b/README.textile
index e69de29..e64011f 100644
--- a/README.textile
+++ b/README.textile
@@ -0,0 +1,26 @@
+h1. jQuery MultiSelect
+
+h2. About
+
+jQuery MultiSelect provide an elegant way to handle multiple options on an input.
+To see examples go to "jQuery MultiSelect page":http://wilkerlucio.github.com/jquery-multiselect/
+
+h2. Instalation
+
+Just copy Javascripts, CSS and Image files in containing folders, see examples.
+
+h2. Requirements
+
+* jQuery 1.4+
+
+h2. Tested on
+
+* IE6+
+* Firefox
+* Safari
+* Chrome
+
+h2. TODO
+
+* Support for values independent from captions
+* Direct integration with select multiple
\ No newline at end of file
|
wilkerlucio/jquery-multiselect
|
62b027b080837c251de987a2b798fc923d0f3e5b
|
remove TODO
|
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index a4babf9..edf8d30 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,494 +1,493 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
BACKSPACE: 8,
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ",",
completions: [],
max_complete_results: 5
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
this.parse_value();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
return this.parse_value(1);
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.add_and_reset();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.observer.bind([KEY.BACKSPACE], (function(__this) {
var __func = function(e) {
var caret;
if (this.values.length <= 0) {
return null;
}
caret = this.selection.get_caret();
if (caret[0] === 0 && caret[1] === 0) {
e.preventDefault();
return this.remove(this.values[this.values.length - 1]);
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.prototype.parse_value = function parse_value(min) {
var _a, _b, _c, value, values;
min = (typeof min !== "undefined" && min !== null) ? min : 0;
values = this.input.val().split(this.options.separator);
if (values.length > min) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.present()) {
this.add(value);
}
}
this.input.val("");
return this.autocomplete.search();
}
};
$.MultiSelect.prototype.add_and_reset = function add_and_reset() {
if (this.autocomplete.val()) {
this.add(this.autocomplete.val());
return this.input.val("");
}
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value, this.values) > -1) {
return null;
}
if (value.blank()) {
return null;
}
value = value.trim();
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
a.html(value.entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
return this.remove(a.data("value"));
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
this.values = $.grep(this.values, function(v) {
return v !== value;
});
this.container.find("a.bit-box").each(function() {
if ($(this).data("value") === value) {
return $(this).remove();
}
});
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values.join(this.options.separator));
};
// Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
// Selection Helper
- // TODO: support IE
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
var r;
// For IE
if (document.selection) {
r = document.selection.createRange().duplicate();
r.moveEnd('character', this.input.value.length);
if (r.text === '') {
return [this.input.value.length, this.input.value.length];
} else {
return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)];
// Others
}
} else {
return [this.input.selectionStart, this.input.selectionEnd];
}
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
// Resizable Input Helper
$.MultiSelect.ResizableInput = function ResizableInput(element) {
this.input = $(element);
this.create_measurer();
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
return this;
};
$.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
var measurer;
if ($("#__jquery_multiselect_measurer")[0] === undefined) {
measurer = $(document.createElement("div"));
measurer.attr("id", "__jquery_multiselect_measurer");
measurer.css({
position: "absolute",
left: "-1000px",
top: "-1000px"
});
$(document.body).append(measurer);
}
this.measurer = $("#__jquery_multiselect_measurer:first");
return this.measurer.css({
fontSize: this.input.css('font-size'),
fontFamily: this.input.css('font-family')
});
};
$.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
this.measurer.html(this.input.val().entitizeHTML() + 'MM');
return this.measurer.innerWidth();
};
$.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
return this.input.css("width", this.calculate_width() + "px");
};
// AutoComplete Helper
$.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) {
this.multiselect = multiselect;
this.input = this.multiselect.input;
this.completions = completions;
this.matches = [];
this.create_elements();
this.bind_events();
return this;
};
$.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() {
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect-autocomplete");
this.container.css("width", this.multiselect.container.outerWidth());
this.container.css("display", "none");
this.container.append(this.def);
this.list = $(document.createElement("ul"));
this.list.addClass("feed");
this.container.append(this.list);
return this.multiselect.container.after(this.container);
};
$.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() {
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.multiselect.observer.bind(KEY.UP, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_up();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.multiselect.observer.bind(KEY.DOWN, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_down();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.AutoComplete.prototype.search = function search() {
var _a, _b, def, i, item, option;
if (this.input.val().trim() === this.query) {
return null;
}
// dont do operation if query is same
this.query = this.input.val().trim();
this.list.html("");
// clear list
this.current = 0;
if (this.query.present()) {
this.container.css("display", "block");
this.matches = this.matching_completions(this.query);
def = this.create_item("Add <em>" + this.query + "</em>");
def.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [0])));
_a = this.matches;
for (i = 0, _b = _a.length; i < _b; i++) {
option = _a[i];
item = this.create_item(this.highlight(option, this.query));
item.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [i + 1])));
}
this.matches.unshift(this.query);
return this.select_index(0);
} else {
this.container.css("display", "none");
this.query = null;
return this.query;
}
};
$.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) {
var items;
items = this.list.find("li");
items.removeClass("auto-focus");
items.filter(":eq(" + (index) + ")").addClass("auto-focus");
this.current = index;
return this.current;
};
$.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() {
var next;
next = this.current + 1;
if (next >= this.matches.length) {
next = 0;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() {
var next;
next = this.current - 1;
if (next < 0) {
next = this.matches.length - 1;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) {
var item;
item = $(document.createElement("li"));
item.click((function(__this) {
var __func = function() {
this.multiselect.add_and_reset();
this.search();
return this.input.focus();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
item.html(text);
this.list.append(item);
return item;
};
$.MultiSelect.AutoComplete.prototype.val = function val() {
return this.matches[this.current];
};
$.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) {
var reg;
reg = "(" + (RegExp.escape(highlight)) + ")";
return text.replace(new RegExp(reg, "gi"), '<em>$1</em>');
};
$.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) {
var count, reg;
reg = new RegExp(RegExp.escape(text), "i");
count = 0;
return $.grep(this.completions, (function(__this) {
var __func = function(c) {
if (count >= this.multiselect.options.max_complete_results) {
return false;
}
if ($.inArray(c, this.multiselect.values) > -1) {
return false;
}
if (c.match(reg)) {
count++;
return true;
} else {
return false;
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// Hook jQuery extension
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
trim: function trim() {
return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '');
},
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
blank: function blank() {
return this.trim().length === 0;
},
present: function present() {
return !this.blank();
}
});
RegExp.escape = function escape(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index 394caed..956ffd7 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,341 +1,340 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
BACKSPACE: 8
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
completions: [],
max_complete_results: 5
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
@parse_value()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection: new $.MultiSelect.Selection(@input)
@resizable: new $.MultiSelect.ResizableInput(@input)
@observer: new $.MultiSelect.InputObserver(@input)
@autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
@parse_value(1)
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
e.preventDefault()
@add_and_reset()
@observer.bind [KEY.BACKSPACE], (e) =>
return if @values.length <= 0
caret = @selection.get_caret()
if caret[0] == 0 and caret[1] == 0
e.preventDefault()
@remove(@values[@values.length - 1])
parse_value: (min) ->
min ?= 0
values: @input.val().split(@options.separator)
if values.length > min
for value in values
@add value if value.present()
@input.val("")
@autocomplete.search()
add_and_reset: ->
if @autocomplete.val()
@add(@autocomplete.val())
@input.val("")
# add new element
add: (value) ->
return if $.inArray(value, @values) > -1
return if value.blank()
value = value.trim()
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
a.html(value.entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
@values: $.grep @values, (v) -> v != value
@container.find("a.bit-box").each ->
$(this).remove() if $(this).data("value") == value
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values.join(@options.separator))
# Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
# Selection Helper
- # TODO: support IE
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
# For IE
if document.selection
r: document.selection.createRange().duplicate()
r.moveEnd('character', @input.value.length)
if r.text == ''
[@input.value.length, @input.value.length]
else
[@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)]
# Others
else
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart: begin
@input.selectionEnd: end
set_caret_at_end: ->
@set_caret(@input.value.length)
# Resizable Input Helper
class $.MultiSelect.ResizableInput
constructor: (element) ->
@input: $(element)
@create_measurer()
@input.keypress(@set_width <- this)
@input.keyup(@set_width <- this)
@input.change(@set_width <- this)
create_measurer: ->
if $("#__jquery_multiselect_measurer")[0] == undefined
measurer: $(document.createElement("div"))
measurer.attr("id", "__jquery_multiselect_measurer")
measurer.css {
position: "absolute"
left: "-1000px"
top: "-1000px"
}
$(document.body).append(measurer)
@measurer: $("#__jquery_multiselect_measurer:first")
@measurer.css {
fontSize: @input.css('font-size')
fontFamily: @input.css('font-family')
}
calculate_width: ->
@measurer.html(@input.val().entitizeHTML() + 'MM')
@measurer.innerWidth()
set_width: ->
@input.css("width", @calculate_width() + "px")
# AutoComplete Helper
class $.MultiSelect.AutoComplete
constructor: (multiselect, completions) ->
@multiselect: multiselect
@input: @multiselect.input
@completions: completions
@matches: []
@create_elements()
@bind_events()
create_elements: ->
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect-autocomplete")
@container.css("width", @multiselect.container.outerWidth())
@container.css("display", "none")
@container.append(@def)
@list: $(document.createElement("ul"))
@list.addClass("feed")
@container.append(@list)
@multiselect.container.after(@container)
bind_events: ->
@input.keypress(@search <- this)
@input.keyup(@search <- this)
@input.change(@search <- this)
@multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up()
@multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down()
search: ->
return if @input.val().trim() == @query # dont do operation if query is same
@query: @input.val().trim()
@list.html("") # clear list
@current: 0
if @query.present()
@container.css("display", "block")
@matches: @matching_completions(@query)
def: @create_item("Add <em>" + @query + "</em>")
def.mouseover(@select_index <- this, 0)
for option, i in @matches
item: @create_item(@highlight(option, @query))
item.mouseover(@select_index <- this, i + 1)
@matches.unshift(@query)
@select_index(0)
else
@container.css("display", "none")
@query: null
select_index: (index) ->
items: @list.find("li")
items.removeClass("auto-focus")
items.filter(":eq(${index})").addClass("auto-focus")
@current: index
navigate_down: ->
next: @current + 1
next: 0 if next >= @matches.length
@select_index(next)
navigate_up: ->
next: @current - 1
next: @matches.length - 1 if next < 0
@select_index(next)
create_item: (text, highlight) ->
item: $(document.createElement("li"))
item.click =>
@multiselect.add_and_reset()
@search()
@input.focus()
item.html(text)
@list.append(item)
item
val: ->
@matches[@current]
highlight: (text, highlight) ->
reg: "(${RegExp.escape(highlight)})"
text.replace(new RegExp(reg, "gi"), '<em>$1</em>')
matching_completions: (text) ->
reg: new RegExp(RegExp.escape(text), "i")
count: 0
$.grep @completions, (c) =>
return false if count >= @multiselect.options.max_complete_results
return false if $.inArray(c, @multiselect.values) > -1
if c.match(reg)
count++
true
else
false
# Hook jQuery extension
$.fn.multiselect: (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '')
entitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
unentitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
blank: -> this.trim().length == 0
present: -> not @blank()
};
RegExp.escape: (str) ->
String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
wilkerlucio/jquery-multiselect
|
e0ab1a6ed6d9da0e5807ffff84eefdd220185673
|
fixed trim
|
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index 60b592f..a4babf9 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,494 +1,494 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
BACKSPACE: 8,
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ",",
completions: [],
max_complete_results: 5
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
this.parse_value();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
return this.parse_value(1);
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.add_and_reset();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.observer.bind([KEY.BACKSPACE], (function(__this) {
var __func = function(e) {
var caret;
if (this.values.length <= 0) {
return null;
}
caret = this.selection.get_caret();
if (caret[0] === 0 && caret[1] === 0) {
e.preventDefault();
return this.remove(this.values[this.values.length - 1]);
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.prototype.parse_value = function parse_value(min) {
var _a, _b, _c, value, values;
min = (typeof min !== "undefined" && min !== null) ? min : 0;
values = this.input.val().split(this.options.separator);
if (values.length > min) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.present()) {
this.add(value);
}
}
this.input.val("");
return this.autocomplete.search();
}
};
$.MultiSelect.prototype.add_and_reset = function add_and_reset() {
if (this.autocomplete.val()) {
this.add(this.autocomplete.val());
return this.input.val("");
}
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value, this.values) > -1) {
return null;
}
if (value.blank()) {
return null;
}
value = value.trim();
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
a.html(value.entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
return this.remove(a.data("value"));
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
this.values = $.grep(this.values, function(v) {
return v !== value;
});
this.container.find("a.bit-box").each(function() {
if ($(this).data("value") === value) {
return $(this).remove();
}
});
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values.join(this.options.separator));
};
// Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
// Selection Helper
// TODO: support IE
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
var r;
// For IE
if (document.selection) {
r = document.selection.createRange().duplicate();
r.moveEnd('character', this.input.value.length);
if (r.text === '') {
return [this.input.value.length, this.input.value.length];
} else {
return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)];
// Others
}
} else {
return [this.input.selectionStart, this.input.selectionEnd];
}
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
// Resizable Input Helper
$.MultiSelect.ResizableInput = function ResizableInput(element) {
this.input = $(element);
this.create_measurer();
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
return this;
};
$.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
var measurer;
if ($("#__jquery_multiselect_measurer")[0] === undefined) {
measurer = $(document.createElement("div"));
measurer.attr("id", "__jquery_multiselect_measurer");
measurer.css({
position: "absolute",
left: "-1000px",
top: "-1000px"
});
$(document.body).append(measurer);
}
this.measurer = $("#__jquery_multiselect_measurer:first");
return this.measurer.css({
fontSize: this.input.css('font-size'),
fontFamily: this.input.css('font-family')
});
};
$.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
this.measurer.html(this.input.val().entitizeHTML() + 'MM');
return this.measurer.innerWidth();
};
$.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
return this.input.css("width", this.calculate_width() + "px");
};
// AutoComplete Helper
$.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) {
this.multiselect = multiselect;
this.input = this.multiselect.input;
this.completions = completions;
this.matches = [];
this.create_elements();
this.bind_events();
return this;
};
$.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() {
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect-autocomplete");
this.container.css("width", this.multiselect.container.outerWidth());
this.container.css("display", "none");
this.container.append(this.def);
this.list = $(document.createElement("ul"));
this.list.addClass("feed");
this.container.append(this.list);
return this.multiselect.container.after(this.container);
};
$.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() {
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.multiselect.observer.bind(KEY.UP, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_up();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.multiselect.observer.bind(KEY.DOWN, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_down();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.AutoComplete.prototype.search = function search() {
var _a, _b, def, i, item, option;
if (this.input.val().trim() === this.query) {
return null;
}
// dont do operation if query is same
this.query = this.input.val().trim();
this.list.html("");
// clear list
this.current = 0;
if (this.query.present()) {
this.container.css("display", "block");
this.matches = this.matching_completions(this.query);
def = this.create_item("Add <em>" + this.query + "</em>");
def.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [0])));
_a = this.matches;
for (i = 0, _b = _a.length; i < _b; i++) {
option = _a[i];
item = this.create_item(this.highlight(option, this.query));
item.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [i + 1])));
}
this.matches.unshift(this.query);
return this.select_index(0);
} else {
this.container.css("display", "none");
this.query = null;
return this.query;
}
};
$.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) {
var items;
items = this.list.find("li");
items.removeClass("auto-focus");
items.filter(":eq(" + (index) + ")").addClass("auto-focus");
this.current = index;
return this.current;
};
$.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() {
var next;
next = this.current + 1;
if (next >= this.matches.length) {
next = 0;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() {
var next;
next = this.current - 1;
if (next < 0) {
next = this.matches.length - 1;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) {
var item;
item = $(document.createElement("li"));
item.click((function(__this) {
var __func = function() {
this.multiselect.add_and_reset();
this.search();
return this.input.focus();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
item.html(text);
this.list.append(item);
return item;
};
$.MultiSelect.AutoComplete.prototype.val = function val() {
return this.matches[this.current];
};
$.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) {
var reg;
reg = "(" + (RegExp.escape(highlight)) + ")";
return text.replace(new RegExp(reg, "gi"), '<em>$1</em>');
};
$.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) {
var count, reg;
reg = new RegExp(RegExp.escape(text), "i");
count = 0;
return $.grep(this.completions, (function(__this) {
var __func = function(c) {
if (count >= this.multiselect.options.max_complete_results) {
return false;
}
if ($.inArray(c, this.multiselect.values) > -1) {
return false;
}
if (c.match(reg)) {
count++;
return true;
} else {
return false;
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// Hook jQuery extension
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
trim: function trim() {
- return this.replace(/[\r\n\s]/g, '');
+ return this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '');
},
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
blank: function blank() {
return this.trim().length === 0;
},
present: function present() {
return !this.blank();
}
});
RegExp.escape = function escape(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index 53734de..394caed 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,341 +1,341 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
BACKSPACE: 8
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
completions: [],
max_complete_results: 5
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
@parse_value()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection: new $.MultiSelect.Selection(@input)
@resizable: new $.MultiSelect.ResizableInput(@input)
@observer: new $.MultiSelect.InputObserver(@input)
@autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
@parse_value(1)
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
e.preventDefault()
@add_and_reset()
@observer.bind [KEY.BACKSPACE], (e) =>
return if @values.length <= 0
caret = @selection.get_caret()
if caret[0] == 0 and caret[1] == 0
e.preventDefault()
@remove(@values[@values.length - 1])
parse_value: (min) ->
min ?= 0
values: @input.val().split(@options.separator)
if values.length > min
for value in values
@add value if value.present()
@input.val("")
@autocomplete.search()
add_and_reset: ->
if @autocomplete.val()
@add(@autocomplete.val())
@input.val("")
# add new element
add: (value) ->
return if $.inArray(value, @values) > -1
return if value.blank()
value = value.trim()
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
a.html(value.entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
@values: $.grep @values, (v) -> v != value
@container.find("a.bit-box").each ->
$(this).remove() if $(this).data("value") == value
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values.join(@options.separator))
# Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
# Selection Helper
# TODO: support IE
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
# For IE
if document.selection
r: document.selection.createRange().duplicate()
r.moveEnd('character', @input.value.length)
if r.text == ''
[@input.value.length, @input.value.length]
else
[@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)]
# Others
else
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart: begin
@input.selectionEnd: end
set_caret_at_end: ->
@set_caret(@input.value.length)
# Resizable Input Helper
class $.MultiSelect.ResizableInput
constructor: (element) ->
@input: $(element)
@create_measurer()
@input.keypress(@set_width <- this)
@input.keyup(@set_width <- this)
@input.change(@set_width <- this)
create_measurer: ->
if $("#__jquery_multiselect_measurer")[0] == undefined
measurer: $(document.createElement("div"))
measurer.attr("id", "__jquery_multiselect_measurer")
measurer.css {
position: "absolute"
left: "-1000px"
top: "-1000px"
}
$(document.body).append(measurer)
@measurer: $("#__jquery_multiselect_measurer:first")
@measurer.css {
fontSize: @input.css('font-size')
fontFamily: @input.css('font-family')
}
calculate_width: ->
@measurer.html(@input.val().entitizeHTML() + 'MM')
@measurer.innerWidth()
set_width: ->
@input.css("width", @calculate_width() + "px")
# AutoComplete Helper
class $.MultiSelect.AutoComplete
constructor: (multiselect, completions) ->
@multiselect: multiselect
@input: @multiselect.input
@completions: completions
@matches: []
@create_elements()
@bind_events()
create_elements: ->
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect-autocomplete")
@container.css("width", @multiselect.container.outerWidth())
@container.css("display", "none")
@container.append(@def)
@list: $(document.createElement("ul"))
@list.addClass("feed")
@container.append(@list)
@multiselect.container.after(@container)
bind_events: ->
@input.keypress(@search <- this)
@input.keyup(@search <- this)
@input.change(@search <- this)
@multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up()
@multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down()
search: ->
return if @input.val().trim() == @query # dont do operation if query is same
@query: @input.val().trim()
@list.html("") # clear list
@current: 0
if @query.present()
@container.css("display", "block")
@matches: @matching_completions(@query)
def: @create_item("Add <em>" + @query + "</em>")
def.mouseover(@select_index <- this, 0)
for option, i in @matches
item: @create_item(@highlight(option, @query))
item.mouseover(@select_index <- this, i + 1)
@matches.unshift(@query)
@select_index(0)
else
@container.css("display", "none")
@query: null
select_index: (index) ->
items: @list.find("li")
items.removeClass("auto-focus")
items.filter(":eq(${index})").addClass("auto-focus")
@current: index
navigate_down: ->
next: @current + 1
next: 0 if next >= @matches.length
@select_index(next)
navigate_up: ->
next: @current - 1
next: @matches.length - 1 if next < 0
@select_index(next)
create_item: (text, highlight) ->
item: $(document.createElement("li"))
item.click =>
@multiselect.add_and_reset()
@search()
@input.focus()
item.html(text)
@list.append(item)
item
val: ->
@matches[@current]
highlight: (text, highlight) ->
reg: "(${RegExp.escape(highlight)})"
text.replace(new RegExp(reg, "gi"), '<em>$1</em>')
matching_completions: (text) ->
reg: new RegExp(RegExp.escape(text), "i")
count: 0
$.grep @completions, (c) =>
return false if count >= @multiselect.options.max_complete_results
return false if $.inArray(c, @multiselect.values) > -1
if c.match(reg)
count++
true
else
false
# Hook jQuery extension
$.fn.multiselect: (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
- trim: -> this.replace(/[\r\n\s]/g, '')
+ trim: -> this.replace(/^[\r\n\s]/g, '').replace(/[\r\n\s]$/g, '')
entitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
unentitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
blank: -> this.trim().length == 0
present: -> not @blank()
};
RegExp.escape: (str) ->
String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
wilkerlucio/jquery-multiselect
|
e808dfd1cd9e7df5459273f4fc3475f53e5ba2a9
|
get caret on IE
|
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index 6892247..60b592f 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,481 +1,494 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
BACKSPACE: 8,
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ",",
completions: [],
max_complete_results: 5
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
this.parse_value();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
return this.parse_value(1);
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.add_and_reset();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.observer.bind([KEY.BACKSPACE], (function(__this) {
var __func = function(e) {
var caret;
if (this.values.length <= 0) {
return null;
}
caret = this.selection.get_caret();
if (caret[0] === 0 && caret[1] === 0) {
e.preventDefault();
return this.remove(this.values[this.values.length - 1]);
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.prototype.parse_value = function parse_value(min) {
var _a, _b, _c, value, values;
min = (typeof min !== "undefined" && min !== null) ? min : 0;
values = this.input.val().split(this.options.separator);
if (values.length > min) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.present()) {
this.add(value);
}
}
this.input.val("");
return this.autocomplete.search();
}
};
$.MultiSelect.prototype.add_and_reset = function add_and_reset() {
if (this.autocomplete.val()) {
this.add(this.autocomplete.val());
return this.input.val("");
}
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value, this.values) > -1) {
return null;
}
if (value.blank()) {
return null;
}
value = value.trim();
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
a.html(value.entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
return this.remove(a.data("value"));
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
this.values = $.grep(this.values, function(v) {
return v !== value;
});
this.container.find("a.bit-box").each(function() {
if ($(this).data("value") === value) {
return $(this).remove();
}
});
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values.join(this.options.separator));
};
// Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
// Selection Helper
// TODO: support IE
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
- return [this.input.selectionStart, this.input.selectionEnd];
+ var r;
+ // For IE
+ if (document.selection) {
+ r = document.selection.createRange().duplicate();
+ r.moveEnd('character', this.input.value.length);
+ if (r.text === '') {
+ return [this.input.value.length, this.input.value.length];
+ } else {
+ return [this.input.value.lastIndexOf(r.text), this.input.value.lastIndexOf(r.text)];
+ // Others
+ }
+ } else {
+ return [this.input.selectionStart, this.input.selectionEnd];
+ }
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
// Resizable Input Helper
$.MultiSelect.ResizableInput = function ResizableInput(element) {
this.input = $(element);
this.create_measurer();
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
return this;
};
$.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
var measurer;
if ($("#__jquery_multiselect_measurer")[0] === undefined) {
measurer = $(document.createElement("div"));
measurer.attr("id", "__jquery_multiselect_measurer");
measurer.css({
position: "absolute",
left: "-1000px",
top: "-1000px"
});
$(document.body).append(measurer);
}
this.measurer = $("#__jquery_multiselect_measurer:first");
return this.measurer.css({
fontSize: this.input.css('font-size'),
fontFamily: this.input.css('font-family')
});
};
$.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
this.measurer.html(this.input.val().entitizeHTML() + 'MM');
return this.measurer.innerWidth();
};
$.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
return this.input.css("width", this.calculate_width() + "px");
};
// AutoComplete Helper
$.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) {
this.multiselect = multiselect;
this.input = this.multiselect.input;
this.completions = completions;
this.matches = [];
this.create_elements();
this.bind_events();
return this;
};
$.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() {
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect-autocomplete");
this.container.css("width", this.multiselect.container.outerWidth());
this.container.css("display", "none");
this.container.append(this.def);
this.list = $(document.createElement("ul"));
this.list.addClass("feed");
this.container.append(this.list);
return this.multiselect.container.after(this.container);
};
$.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() {
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.multiselect.observer.bind(KEY.UP, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_up();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.multiselect.observer.bind(KEY.DOWN, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_down();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.AutoComplete.prototype.search = function search() {
var _a, _b, def, i, item, option;
if (this.input.val().trim() === this.query) {
return null;
}
// dont do operation if query is same
this.query = this.input.val().trim();
this.list.html("");
// clear list
this.current = 0;
if (this.query.present()) {
this.container.css("display", "block");
this.matches = this.matching_completions(this.query);
def = this.create_item("Add <em>" + this.query + "</em>");
def.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [0])));
_a = this.matches;
for (i = 0, _b = _a.length; i < _b; i++) {
option = _a[i];
item = this.create_item(this.highlight(option, this.query));
item.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [i + 1])));
}
this.matches.unshift(this.query);
return this.select_index(0);
} else {
this.container.css("display", "none");
this.query = null;
return this.query;
}
};
$.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) {
var items;
items = this.list.find("li");
items.removeClass("auto-focus");
items.filter(":eq(" + (index) + ")").addClass("auto-focus");
this.current = index;
return this.current;
};
$.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() {
var next;
next = this.current + 1;
if (next >= this.matches.length) {
next = 0;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() {
var next;
next = this.current - 1;
if (next < 0) {
next = this.matches.length - 1;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) {
var item;
item = $(document.createElement("li"));
item.click((function(__this) {
var __func = function() {
this.multiselect.add_and_reset();
this.search();
return this.input.focus();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
item.html(text);
this.list.append(item);
return item;
};
$.MultiSelect.AutoComplete.prototype.val = function val() {
return this.matches[this.current];
};
$.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) {
var reg;
reg = "(" + (RegExp.escape(highlight)) + ")";
return text.replace(new RegExp(reg, "gi"), '<em>$1</em>');
};
$.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) {
var count, reg;
reg = new RegExp(RegExp.escape(text), "i");
count = 0;
return $.grep(this.completions, (function(__this) {
var __func = function(c) {
if (count >= this.multiselect.options.max_complete_results) {
return false;
}
if ($.inArray(c, this.multiselect.values) > -1) {
return false;
}
if (c.match(reg)) {
count++;
return true;
} else {
return false;
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// Hook jQuery extension
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
trim: function trim() {
return this.replace(/[\r\n\s]/g, '');
},
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
blank: function blank() {
return this.trim().length === 0;
},
present: function present() {
return !this.blank();
}
});
RegExp.escape = function escape(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index 43524dd..53734de 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,330 +1,341 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
BACKSPACE: 8
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
completions: [],
max_complete_results: 5
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
@parse_value()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection: new $.MultiSelect.Selection(@input)
@resizable: new $.MultiSelect.ResizableInput(@input)
@observer: new $.MultiSelect.InputObserver(@input)
@autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
@parse_value(1)
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
e.preventDefault()
@add_and_reset()
@observer.bind [KEY.BACKSPACE], (e) =>
return if @values.length <= 0
caret = @selection.get_caret()
if caret[0] == 0 and caret[1] == 0
e.preventDefault()
@remove(@values[@values.length - 1])
parse_value: (min) ->
min ?= 0
values: @input.val().split(@options.separator)
if values.length > min
for value in values
@add value if value.present()
@input.val("")
@autocomplete.search()
add_and_reset: ->
if @autocomplete.val()
@add(@autocomplete.val())
@input.val("")
# add new element
add: (value) ->
return if $.inArray(value, @values) > -1
return if value.blank()
value = value.trim()
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
a.html(value.entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
@values: $.grep @values, (v) -> v != value
@container.find("a.bit-box").each ->
$(this).remove() if $(this).data("value") == value
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values.join(@options.separator))
# Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
# Selection Helper
# TODO: support IE
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
- [@input.selectionStart, @input.selectionEnd]
+ # For IE
+ if document.selection
+ r: document.selection.createRange().duplicate()
+ r.moveEnd('character', @input.value.length)
+
+ if r.text == ''
+ [@input.value.length, @input.value.length]
+ else
+ [@input.value.lastIndexOf(r.text), @input.value.lastIndexOf(r.text)]
+ # Others
+ else
+ [@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart: begin
@input.selectionEnd: end
set_caret_at_end: ->
@set_caret(@input.value.length)
# Resizable Input Helper
class $.MultiSelect.ResizableInput
constructor: (element) ->
@input: $(element)
@create_measurer()
@input.keypress(@set_width <- this)
@input.keyup(@set_width <- this)
@input.change(@set_width <- this)
create_measurer: ->
if $("#__jquery_multiselect_measurer")[0] == undefined
measurer: $(document.createElement("div"))
measurer.attr("id", "__jquery_multiselect_measurer")
measurer.css {
position: "absolute"
left: "-1000px"
top: "-1000px"
}
$(document.body).append(measurer)
@measurer: $("#__jquery_multiselect_measurer:first")
@measurer.css {
fontSize: @input.css('font-size')
fontFamily: @input.css('font-family')
}
calculate_width: ->
@measurer.html(@input.val().entitizeHTML() + 'MM')
@measurer.innerWidth()
set_width: ->
@input.css("width", @calculate_width() + "px")
# AutoComplete Helper
class $.MultiSelect.AutoComplete
constructor: (multiselect, completions) ->
@multiselect: multiselect
@input: @multiselect.input
@completions: completions
@matches: []
@create_elements()
@bind_events()
create_elements: ->
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect-autocomplete")
@container.css("width", @multiselect.container.outerWidth())
@container.css("display", "none")
@container.append(@def)
@list: $(document.createElement("ul"))
@list.addClass("feed")
@container.append(@list)
@multiselect.container.after(@container)
bind_events: ->
@input.keypress(@search <- this)
@input.keyup(@search <- this)
@input.change(@search <- this)
@multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up()
@multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down()
search: ->
return if @input.val().trim() == @query # dont do operation if query is same
@query: @input.val().trim()
@list.html("") # clear list
@current: 0
if @query.present()
@container.css("display", "block")
@matches: @matching_completions(@query)
def: @create_item("Add <em>" + @query + "</em>")
def.mouseover(@select_index <- this, 0)
for option, i in @matches
item: @create_item(@highlight(option, @query))
item.mouseover(@select_index <- this, i + 1)
@matches.unshift(@query)
@select_index(0)
else
@container.css("display", "none")
@query: null
select_index: (index) ->
items: @list.find("li")
items.removeClass("auto-focus")
items.filter(":eq(${index})").addClass("auto-focus")
@current: index
navigate_down: ->
next: @current + 1
next: 0 if next >= @matches.length
@select_index(next)
navigate_up: ->
next: @current - 1
next: @matches.length - 1 if next < 0
@select_index(next)
create_item: (text, highlight) ->
item: $(document.createElement("li"))
item.click =>
@multiselect.add_and_reset()
@search()
@input.focus()
item.html(text)
@list.append(item)
item
val: ->
@matches[@current]
highlight: (text, highlight) ->
reg: "(${RegExp.escape(highlight)})"
text.replace(new RegExp(reg, "gi"), '<em>$1</em>')
matching_completions: (text) ->
reg: new RegExp(RegExp.escape(text), "i")
count: 0
$.grep @completions, (c) =>
return false if count >= @multiselect.options.max_complete_results
return false if $.inArray(c, @multiselect.values) > -1
if c.match(reg)
count++
true
else
false
# Hook jQuery extension
$.fn.multiselect: (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
trim: -> this.replace(/[\r\n\s]/g, '')
entitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
unentitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
blank: -> this.trim().length == 0
present: -> not @blank()
};
RegExp.escape: (str) ->
String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
wilkerlucio/jquery-multiselect
|
e2850e5bd5c912e15345c173fc7b76296cb3c8bc
|
remove item with backspace
|
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index c8ff576..6892247 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,460 +1,481 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
+ BACKSPACE: 8,
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ",",
completions: [],
max_complete_results: 5
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
this.parse_value();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
return this.parse_value(1);
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
- return this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
+ this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.add_and_reset();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
+ return this.observer.bind([KEY.BACKSPACE], (function(__this) {
+ var __func = function(e) {
+ var caret;
+ if (this.values.length <= 0) {
+ return null;
+ }
+ caret = this.selection.get_caret();
+ if (caret[0] === 0 && caret[1] === 0) {
+ e.preventDefault();
+ return this.remove(this.values[this.values.length - 1]);
+ }
+ };
+ return (function() {
+ return __func.apply(__this, arguments);
+ });
+ })(this));
};
$.MultiSelect.prototype.parse_value = function parse_value(min) {
var _a, _b, _c, value, values;
min = (typeof min !== "undefined" && min !== null) ? min : 0;
values = this.input.val().split(this.options.separator);
if (values.length > min) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.present()) {
this.add(value);
}
}
this.input.val("");
return this.autocomplete.search();
}
};
$.MultiSelect.prototype.add_and_reset = function add_and_reset() {
if (this.autocomplete.val()) {
this.add(this.autocomplete.val());
return this.input.val("");
}
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value, this.values) > -1) {
return null;
}
if (value.blank()) {
return null;
}
value = value.trim();
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
a.html(value.entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
- this.remove(a.data("value"));
- return a.remove();
+ return this.remove(a.data("value"));
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
this.values = $.grep(this.values, function(v) {
return v !== value;
});
+ this.container.find("a.bit-box").each(function() {
+ if ($(this).data("value") === value) {
+ return $(this).remove();
+ }
+ });
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values.join(this.options.separator));
};
// Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
// Selection Helper
// TODO: support IE
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
return [this.input.selectionStart, this.input.selectionEnd];
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
// Resizable Input Helper
$.MultiSelect.ResizableInput = function ResizableInput(element) {
this.input = $(element);
this.create_measurer();
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
return this;
};
$.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
var measurer;
if ($("#__jquery_multiselect_measurer")[0] === undefined) {
measurer = $(document.createElement("div"));
measurer.attr("id", "__jquery_multiselect_measurer");
measurer.css({
position: "absolute",
left: "-1000px",
top: "-1000px"
});
$(document.body).append(measurer);
}
this.measurer = $("#__jquery_multiselect_measurer:first");
return this.measurer.css({
fontSize: this.input.css('font-size'),
fontFamily: this.input.css('font-family')
});
};
$.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
this.measurer.html(this.input.val().entitizeHTML() + 'MM');
return this.measurer.innerWidth();
};
$.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
return this.input.css("width", this.calculate_width() + "px");
};
// AutoComplete Helper
$.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) {
this.multiselect = multiselect;
this.input = this.multiselect.input;
this.completions = completions;
this.matches = [];
this.create_elements();
this.bind_events();
return this;
};
$.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() {
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect-autocomplete");
this.container.css("width", this.multiselect.container.outerWidth());
this.container.css("display", "none");
this.container.append(this.def);
this.list = $(document.createElement("ul"));
this.list.addClass("feed");
this.container.append(this.list);
return this.multiselect.container.after(this.container);
};
$.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() {
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.multiselect.observer.bind(KEY.UP, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_up();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.multiselect.observer.bind(KEY.DOWN, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_down();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.AutoComplete.prototype.search = function search() {
var _a, _b, def, i, item, option;
if (this.input.val().trim() === this.query) {
return null;
}
// dont do operation if query is same
this.query = this.input.val().trim();
this.list.html("");
// clear list
this.current = 0;
if (this.query.present()) {
this.container.css("display", "block");
this.matches = this.matching_completions(this.query);
def = this.create_item("Add <em>" + this.query + "</em>");
def.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [0])));
_a = this.matches;
for (i = 0, _b = _a.length; i < _b; i++) {
option = _a[i];
item = this.create_item(this.highlight(option, this.query));
item.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [i + 1])));
}
this.matches.unshift(this.query);
return this.select_index(0);
} else {
this.container.css("display", "none");
this.query = null;
return this.query;
}
};
$.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) {
var items;
items = this.list.find("li");
items.removeClass("auto-focus");
items.filter(":eq(" + (index) + ")").addClass("auto-focus");
this.current = index;
return this.current;
};
$.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() {
var next;
next = this.current + 1;
if (next >= this.matches.length) {
next = 0;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() {
var next;
next = this.current - 1;
if (next < 0) {
next = this.matches.length - 1;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) {
var item;
item = $(document.createElement("li"));
item.click((function(__this) {
var __func = function() {
this.multiselect.add_and_reset();
this.search();
return this.input.focus();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
item.html(text);
this.list.append(item);
return item;
};
$.MultiSelect.AutoComplete.prototype.val = function val() {
return this.matches[this.current];
};
$.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) {
var reg;
reg = "(" + (RegExp.escape(highlight)) + ")";
return text.replace(new RegExp(reg, "gi"), '<em>$1</em>');
};
$.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) {
var count, reg;
reg = new RegExp(RegExp.escape(text), "i");
count = 0;
return $.grep(this.completions, (function(__this) {
var __func = function(c) {
if (count >= this.multiselect.options.max_complete_results) {
return false;
}
if ($.inArray(c, this.multiselect.values) > -1) {
return false;
}
if (c.match(reg)) {
count++;
return true;
} else {
return false;
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// Hook jQuery extension
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
trim: function trim() {
return this.replace(/[\r\n\s]/g, '');
},
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
blank: function blank() {
return this.trim().length === 0;
},
present: function present() {
return !this.blank();
}
});
RegExp.escape = function escape(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index 04b44ed..43524dd 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,320 +1,330 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
+ BACKSPACE: 8
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
completions: [],
max_complete_results: 5
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
@parse_value()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection: new $.MultiSelect.Selection(@input)
@resizable: new $.MultiSelect.ResizableInput(@input)
@observer: new $.MultiSelect.InputObserver(@input)
@autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
@parse_value(1)
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
e.preventDefault()
@add_and_reset()
+
+ @observer.bind [KEY.BACKSPACE], (e) =>
+ return if @values.length <= 0
+ caret = @selection.get_caret()
+
+ if caret[0] == 0 and caret[1] == 0
+ e.preventDefault()
+ @remove(@values[@values.length - 1])
parse_value: (min) ->
min ?= 0
values: @input.val().split(@options.separator)
if values.length > min
for value in values
@add value if value.present()
@input.val("")
@autocomplete.search()
add_and_reset: ->
if @autocomplete.val()
@add(@autocomplete.val())
@input.val("")
# add new element
add: (value) ->
return if $.inArray(value, @values) > -1
return if value.blank()
value = value.trim()
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
a.html(value.entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
- a.remove()
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
@values: $.grep @values, (v) -> v != value
+ @container.find("a.bit-box").each ->
+ $(this).remove() if $(this).data("value") == value
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values.join(@options.separator))
# Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
# Selection Helper
# TODO: support IE
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart: begin
@input.selectionEnd: end
set_caret_at_end: ->
@set_caret(@input.value.length)
# Resizable Input Helper
class $.MultiSelect.ResizableInput
constructor: (element) ->
@input: $(element)
@create_measurer()
@input.keypress(@set_width <- this)
@input.keyup(@set_width <- this)
@input.change(@set_width <- this)
create_measurer: ->
if $("#__jquery_multiselect_measurer")[0] == undefined
measurer: $(document.createElement("div"))
measurer.attr("id", "__jquery_multiselect_measurer")
measurer.css {
position: "absolute"
left: "-1000px"
top: "-1000px"
}
$(document.body).append(measurer)
@measurer: $("#__jquery_multiselect_measurer:first")
@measurer.css {
fontSize: @input.css('font-size')
fontFamily: @input.css('font-family')
}
calculate_width: ->
@measurer.html(@input.val().entitizeHTML() + 'MM')
@measurer.innerWidth()
set_width: ->
@input.css("width", @calculate_width() + "px")
# AutoComplete Helper
class $.MultiSelect.AutoComplete
constructor: (multiselect, completions) ->
@multiselect: multiselect
@input: @multiselect.input
@completions: completions
@matches: []
@create_elements()
@bind_events()
create_elements: ->
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect-autocomplete")
@container.css("width", @multiselect.container.outerWidth())
@container.css("display", "none")
@container.append(@def)
@list: $(document.createElement("ul"))
@list.addClass("feed")
@container.append(@list)
@multiselect.container.after(@container)
bind_events: ->
@input.keypress(@search <- this)
@input.keyup(@search <- this)
@input.change(@search <- this)
@multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up()
@multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down()
search: ->
return if @input.val().trim() == @query # dont do operation if query is same
@query: @input.val().trim()
@list.html("") # clear list
@current: 0
if @query.present()
@container.css("display", "block")
@matches: @matching_completions(@query)
def: @create_item("Add <em>" + @query + "</em>")
def.mouseover(@select_index <- this, 0)
for option, i in @matches
item: @create_item(@highlight(option, @query))
item.mouseover(@select_index <- this, i + 1)
@matches.unshift(@query)
@select_index(0)
else
@container.css("display", "none")
@query: null
select_index: (index) ->
items: @list.find("li")
items.removeClass("auto-focus")
items.filter(":eq(${index})").addClass("auto-focus")
@current: index
navigate_down: ->
next: @current + 1
next: 0 if next >= @matches.length
@select_index(next)
navigate_up: ->
next: @current - 1
next: @matches.length - 1 if next < 0
@select_index(next)
create_item: (text, highlight) ->
item: $(document.createElement("li"))
item.click =>
@multiselect.add_and_reset()
@search()
@input.focus()
item.html(text)
@list.append(item)
item
val: ->
@matches[@current]
highlight: (text, highlight) ->
reg: "(${RegExp.escape(highlight)})"
text.replace(new RegExp(reg, "gi"), '<em>$1</em>')
matching_completions: (text) ->
reg: new RegExp(RegExp.escape(text), "i")
count: 0
$.grep @completions, (c) =>
return false if count >= @multiselect.options.max_complete_results
return false if $.inArray(c, @multiselect.values) > -1
if c.match(reg)
count++
true
else
false
# Hook jQuery extension
$.fn.multiselect: (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
trim: -> this.replace(/[\r\n\s]/g, '')
entitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
unentitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
blank: -> this.trim().length == 0
present: -> not @blank()
};
RegExp.escape: (str) ->
String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
wilkerlucio/jquery-multiselect
|
ea436dbcbcaab7a43b9f68e953a09bdd373662b3
|
IE 6 fixes
|
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index 8f1718a..c8ff576 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,454 +1,460 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ",",
completions: [],
max_complete_results: 5
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
this.parse_value();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
return this.parse_value(1);
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
return this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.add_and_reset();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.prototype.parse_value = function parse_value(min) {
var _a, _b, _c, value, values;
min = (typeof min !== "undefined" && min !== null) ? min : 0;
values = this.input.val().split(this.options.separator);
if (values.length > min) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.present()) {
this.add(value);
}
}
this.input.val("");
return this.autocomplete.search();
}
};
$.MultiSelect.prototype.add_and_reset = function add_and_reset() {
- if (this.autocomplete.value()) {
- this.add(this.autocomplete.value());
+ if (this.autocomplete.val()) {
+ this.add(this.autocomplete.val());
return this.input.val("");
}
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value, this.values) > -1) {
return null;
}
if (value.blank()) {
return null;
}
value = value.trim();
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
a.html(value.entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
this.remove(a.data("value"));
return a.remove();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
this.values = $.grep(this.values, function(v) {
return v !== value;
});
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values.join(this.options.separator));
};
// Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
// Selection Helper
// TODO: support IE
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
return [this.input.selectionStart, this.input.selectionEnd];
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
// Resizable Input Helper
$.MultiSelect.ResizableInput = function ResizableInput(element) {
this.input = $(element);
this.create_measurer();
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
return this;
};
$.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
var measurer;
if ($("#__jquery_multiselect_measurer")[0] === undefined) {
measurer = $(document.createElement("div"));
measurer.attr("id", "__jquery_multiselect_measurer");
measurer.css({
position: "absolute",
left: "-1000px",
top: "-1000px"
});
$(document.body).append(measurer);
}
this.measurer = $("#__jquery_multiselect_measurer:first");
return this.measurer.css({
fontSize: this.input.css('font-size'),
fontFamily: this.input.css('font-family')
});
};
$.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
this.measurer.html(this.input.val().entitizeHTML() + 'MM');
- return parseInt(this.measurer.css("width"));
+ return this.measurer.innerWidth();
};
$.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
return this.input.css("width", this.calculate_width() + "px");
};
// AutoComplete Helper
$.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) {
this.multiselect = multiselect;
this.input = this.multiselect.input;
this.completions = completions;
this.matches = [];
this.create_elements();
this.bind_events();
return this;
};
$.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() {
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect-autocomplete");
this.container.css("width", this.multiselect.container.outerWidth());
+ this.container.css("display", "none");
this.container.append(this.def);
this.list = $(document.createElement("ul"));
this.list.addClass("feed");
this.container.append(this.list);
return this.multiselect.container.after(this.container);
};
$.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() {
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.multiselect.observer.bind(KEY.UP, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_up();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.multiselect.observer.bind(KEY.DOWN, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_down();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.AutoComplete.prototype.search = function search() {
var _a, _b, def, i, item, option;
if (this.input.val().trim() === this.query) {
return null;
}
// dont do operation if query is same
this.query = this.input.val().trim();
this.list.html("");
// clear list
this.current = 0;
if (this.query.present()) {
+ this.container.css("display", "block");
this.matches = this.matching_completions(this.query);
def = this.create_item("Add <em>" + this.query + "</em>");
def.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [0])));
_a = this.matches;
for (i = 0, _b = _a.length; i < _b; i++) {
option = _a[i];
item = this.create_item(this.highlight(option, this.query));
item.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [i + 1])));
}
this.matches.unshift(this.query);
return this.select_index(0);
} else {
+ this.container.css("display", "none");
this.query = null;
return this.query;
}
};
$.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) {
var items;
items = this.list.find("li");
items.removeClass("auto-focus");
items.filter(":eq(" + (index) + ")").addClass("auto-focus");
this.current = index;
return this.current;
};
$.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() {
var next;
next = this.current + 1;
if (next >= this.matches.length) {
next = 0;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() {
var next;
next = this.current - 1;
if (next < 0) {
next = this.matches.length - 1;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) {
var item;
item = $(document.createElement("li"));
item.click((function(__this) {
var __func = function() {
this.multiselect.add_and_reset();
this.search();
return this.input.focus();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
item.html(text);
this.list.append(item);
return item;
};
- $.MultiSelect.AutoComplete.prototype.value = function value() {
+ $.MultiSelect.AutoComplete.prototype.val = function val() {
return this.matches[this.current];
};
$.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) {
var reg;
reg = "(" + (RegExp.escape(highlight)) + ")";
return text.replace(new RegExp(reg, "gi"), '<em>$1</em>');
};
$.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) {
var count, reg;
reg = new RegExp(RegExp.escape(text), "i");
count = 0;
return $.grep(this.completions, (function(__this) {
var __func = function(c) {
if (count >= this.multiselect.options.max_complete_results) {
return false;
}
if ($.inArray(c, this.multiselect.values) > -1) {
return false;
}
if (c.match(reg)) {
count++;
return true;
} else {
return false;
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// Hook jQuery extension
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
+ trim: function trim() {
+ return this.replace(/[\r\n\s]/g, '');
+ },
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
blank: function blank() {
return this.trim().length === 0;
},
present: function present() {
return !this.blank();
}
});
RegExp.escape = function escape(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index 55b16aa..04b44ed 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,316 +1,320 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
completions: [],
max_complete_results: 5
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
@parse_value()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection: new $.MultiSelect.Selection(@input)
@resizable: new $.MultiSelect.ResizableInput(@input)
@observer: new $.MultiSelect.InputObserver(@input)
@autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
@parse_value(1)
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
e.preventDefault()
@add_and_reset()
parse_value: (min) ->
min ?= 0
values: @input.val().split(@options.separator)
if values.length > min
for value in values
@add value if value.present()
@input.val("")
@autocomplete.search()
- add_and_reset: ->
- if @autocomplete.value()
- @add(@autocomplete.value())
+ add_and_reset: ->
+ if @autocomplete.val()
+ @add(@autocomplete.val())
@input.val("")
# add new element
add: (value) ->
return if $.inArray(value, @values) > -1
return if value.blank()
value = value.trim()
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
a.html(value.entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.remove()
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
@values: $.grep @values, (v) -> v != value
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values.join(@options.separator))
# Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
# Selection Helper
# TODO: support IE
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart: begin
@input.selectionEnd: end
set_caret_at_end: ->
@set_caret(@input.value.length)
# Resizable Input Helper
class $.MultiSelect.ResizableInput
constructor: (element) ->
@input: $(element)
@create_measurer()
@input.keypress(@set_width <- this)
@input.keyup(@set_width <- this)
@input.change(@set_width <- this)
create_measurer: ->
if $("#__jquery_multiselect_measurer")[0] == undefined
measurer: $(document.createElement("div"))
measurer.attr("id", "__jquery_multiselect_measurer")
measurer.css {
position: "absolute"
left: "-1000px"
top: "-1000px"
}
$(document.body).append(measurer)
@measurer: $("#__jquery_multiselect_measurer:first")
@measurer.css {
fontSize: @input.css('font-size')
fontFamily: @input.css('font-family')
}
- calculate_width: ->
+ calculate_width: ->
@measurer.html(@input.val().entitizeHTML() + 'MM')
- parseInt(@measurer.css("width"))
+ @measurer.innerWidth()
set_width: ->
@input.css("width", @calculate_width() + "px")
# AutoComplete Helper
class $.MultiSelect.AutoComplete
constructor: (multiselect, completions) ->
@multiselect: multiselect
@input: @multiselect.input
@completions: completions
@matches: []
@create_elements()
@bind_events()
create_elements: ->
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect-autocomplete")
@container.css("width", @multiselect.container.outerWidth())
+ @container.css("display", "none")
@container.append(@def)
@list: $(document.createElement("ul"))
@list.addClass("feed")
@container.append(@list)
@multiselect.container.after(@container)
bind_events: ->
@input.keypress(@search <- this)
@input.keyup(@search <- this)
@input.change(@search <- this)
@multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up()
@multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down()
search: ->
return if @input.val().trim() == @query # dont do operation if query is same
@query: @input.val().trim()
@list.html("") # clear list
@current: 0
if @query.present()
+ @container.css("display", "block")
@matches: @matching_completions(@query)
def: @create_item("Add <em>" + @query + "</em>")
def.mouseover(@select_index <- this, 0)
for option, i in @matches
item: @create_item(@highlight(option, @query))
item.mouseover(@select_index <- this, i + 1)
@matches.unshift(@query)
@select_index(0)
else
+ @container.css("display", "none")
@query: null
select_index: (index) ->
items: @list.find("li")
items.removeClass("auto-focus")
items.filter(":eq(${index})").addClass("auto-focus")
@current: index
navigate_down: ->
next: @current + 1
next: 0 if next >= @matches.length
@select_index(next)
navigate_up: ->
next: @current - 1
next: @matches.length - 1 if next < 0
@select_index(next)
create_item: (text, highlight) ->
item: $(document.createElement("li"))
item.click =>
@multiselect.add_and_reset()
@search()
@input.focus()
item.html(text)
@list.append(item)
item
- value: ->
+ val: ->
@matches[@current]
highlight: (text, highlight) ->
reg: "(${RegExp.escape(highlight)})"
text.replace(new RegExp(reg, "gi"), '<em>$1</em>')
matching_completions: (text) ->
reg: new RegExp(RegExp.escape(text), "i")
count: 0
$.grep @completions, (c) =>
return false if count >= @multiselect.options.max_complete_results
return false if $.inArray(c, @multiselect.values) > -1
if c.match(reg)
count++
true
else
false
# Hook jQuery extension
$.fn.multiselect: (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
- entitizeHTML: -> return this.replace(/</g,'<').replace(/>/g,'>')
- unentitizeHTML: -> return this.replace(/</g,'<').replace(/>/g,'>')
- blank: -> return this.trim().length == 0
- present: -> return not @blank()
+ trim: -> this.replace(/[\r\n\s]/g, '')
+ entitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
+ unentitizeHTML: -> this.replace(/</g,'<').replace(/>/g,'>')
+ blank: -> this.trim().length == 0
+ present: -> not @blank()
};
RegExp.escape: (str) ->
String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
wilkerlucio/jquery-multiselect
|
6877d38c2432cf5ad67c71816c6660c1071af8a6
|
reset on paste or include separator
|
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index ee01531..8f1718a 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,452 +1,454 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ",",
completions: [],
max_complete_results: 5
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
this.parse_value();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
return this.parse_value(1);
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
return this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.add_and_reset();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.prototype.parse_value = function parse_value(min) {
var _a, _b, _c, value, values;
min = (typeof min !== "undefined" && min !== null) ? min : 0;
values = this.input.val().split(this.options.separator);
if (values.length > min) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.present()) {
this.add(value);
}
}
- return this.input.val("");
+ this.input.val("");
+ return this.autocomplete.search();
}
};
$.MultiSelect.prototype.add_and_reset = function add_and_reset() {
if (this.autocomplete.value()) {
this.add(this.autocomplete.value());
return this.input.val("");
}
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value, this.values) > -1) {
return null;
}
if (value.blank()) {
return null;
}
+ value = value.trim();
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
a.html(value.entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
this.remove(a.data("value"));
return a.remove();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
this.values = $.grep(this.values, function(v) {
return v !== value;
});
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values.join(this.options.separator));
};
// Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
// Selection Helper
// TODO: support IE
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
return [this.input.selectionStart, this.input.selectionEnd];
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
// Resizable Input Helper
$.MultiSelect.ResizableInput = function ResizableInput(element) {
this.input = $(element);
this.create_measurer();
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
return this;
};
$.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
var measurer;
if ($("#__jquery_multiselect_measurer")[0] === undefined) {
measurer = $(document.createElement("div"));
measurer.attr("id", "__jquery_multiselect_measurer");
measurer.css({
position: "absolute",
left: "-1000px",
top: "-1000px"
});
$(document.body).append(measurer);
}
this.measurer = $("#__jquery_multiselect_measurer:first");
return this.measurer.css({
fontSize: this.input.css('font-size'),
fontFamily: this.input.css('font-family')
});
};
$.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
this.measurer.html(this.input.val().entitizeHTML() + 'MM');
return parseInt(this.measurer.css("width"));
};
$.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
return this.input.css("width", this.calculate_width() + "px");
};
// AutoComplete Helper
$.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) {
this.multiselect = multiselect;
this.input = this.multiselect.input;
this.completions = completions;
this.matches = [];
this.create_elements();
this.bind_events();
return this;
};
$.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() {
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect-autocomplete");
this.container.css("width", this.multiselect.container.outerWidth());
this.container.append(this.def);
this.list = $(document.createElement("ul"));
this.list.addClass("feed");
this.container.append(this.list);
return this.multiselect.container.after(this.container);
};
$.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() {
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.multiselect.observer.bind(KEY.UP, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_up();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.multiselect.observer.bind(KEY.DOWN, (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.navigate_down();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.AutoComplete.prototype.search = function search() {
var _a, _b, def, i, item, option;
if (this.input.val().trim() === this.query) {
return null;
}
// dont do operation if query is same
this.query = this.input.val().trim();
this.list.html("");
// clear list
this.current = 0;
if (this.query.present()) {
this.matches = this.matching_completions(this.query);
def = this.create_item("Add <em>" + this.query + "</em>");
def.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [0])));
_a = this.matches;
for (i = 0, _b = _a.length; i < _b; i++) {
option = _a[i];
item = this.create_item(this.highlight(option, this.query));
item.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [i + 1])));
}
this.matches.unshift(this.query);
return this.select_index(0);
} else {
this.query = null;
return this.query;
}
};
$.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) {
var items;
items = this.list.find("li");
items.removeClass("auto-focus");
items.filter(":eq(" + (index) + ")").addClass("auto-focus");
this.current = index;
return this.current;
};
$.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() {
var next;
next = this.current + 1;
if (next >= this.matches.length) {
next = 0;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() {
var next;
next = this.current - 1;
if (next < 0) {
next = this.matches.length - 1;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) {
var item;
item = $(document.createElement("li"));
item.click((function(__this) {
var __func = function() {
this.multiselect.add_and_reset();
this.search();
return this.input.focus();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
item.html(text);
this.list.append(item);
return item;
};
$.MultiSelect.AutoComplete.prototype.value = function value() {
return this.matches[this.current];
};
$.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) {
var reg;
reg = "(" + (RegExp.escape(highlight)) + ")";
return text.replace(new RegExp(reg, "gi"), '<em>$1</em>');
};
$.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) {
var count, reg;
reg = new RegExp(RegExp.escape(text), "i");
count = 0;
return $.grep(this.completions, (function(__this) {
var __func = function(c) {
if (count >= this.multiselect.options.max_complete_results) {
return false;
}
if ($.inArray(c, this.multiselect.values) > -1) {
return false;
}
if (c.match(reg)) {
count++;
return true;
} else {
return false;
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// Hook jQuery extension
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
blank: function blank() {
return this.trim().length === 0;
},
present: function present() {
return !this.blank();
}
});
RegExp.escape = function escape(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index 72c1c7f..55b16aa 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,314 +1,316 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
completions: [],
max_complete_results: 5
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
@parse_value()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection: new $.MultiSelect.Selection(@input)
@resizable: new $.MultiSelect.ResizableInput(@input)
@observer: new $.MultiSelect.InputObserver(@input)
@autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
@parse_value(1)
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
e.preventDefault()
@add_and_reset()
parse_value: (min) ->
min ?= 0
values: @input.val().split(@options.separator)
if values.length > min
for value in values
@add value if value.present()
@input.val("")
+ @autocomplete.search()
add_and_reset: ->
if @autocomplete.value()
@add(@autocomplete.value())
@input.val("")
# add new element
add: (value) ->
return if $.inArray(value, @values) > -1
return if value.blank()
+ value = value.trim()
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
a.html(value.entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.remove()
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
@values: $.grep @values, (v) -> v != value
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values.join(@options.separator))
# Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
# Selection Helper
# TODO: support IE
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart: begin
@input.selectionEnd: end
set_caret_at_end: ->
@set_caret(@input.value.length)
# Resizable Input Helper
class $.MultiSelect.ResizableInput
constructor: (element) ->
@input: $(element)
@create_measurer()
@input.keypress(@set_width <- this)
@input.keyup(@set_width <- this)
@input.change(@set_width <- this)
create_measurer: ->
if $("#__jquery_multiselect_measurer")[0] == undefined
measurer: $(document.createElement("div"))
measurer.attr("id", "__jquery_multiselect_measurer")
measurer.css {
position: "absolute"
left: "-1000px"
top: "-1000px"
}
$(document.body).append(measurer)
@measurer: $("#__jquery_multiselect_measurer:first")
@measurer.css {
fontSize: @input.css('font-size')
fontFamily: @input.css('font-family')
}
calculate_width: ->
@measurer.html(@input.val().entitizeHTML() + 'MM')
parseInt(@measurer.css("width"))
set_width: ->
@input.css("width", @calculate_width() + "px")
# AutoComplete Helper
class $.MultiSelect.AutoComplete
constructor: (multiselect, completions) ->
@multiselect: multiselect
@input: @multiselect.input
@completions: completions
@matches: []
@create_elements()
@bind_events()
create_elements: ->
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect-autocomplete")
@container.css("width", @multiselect.container.outerWidth())
@container.append(@def)
@list: $(document.createElement("ul"))
@list.addClass("feed")
@container.append(@list)
@multiselect.container.after(@container)
bind_events: ->
@input.keypress(@search <- this)
@input.keyup(@search <- this)
@input.change(@search <- this)
@multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up()
@multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down()
search: ->
return if @input.val().trim() == @query # dont do operation if query is same
@query: @input.val().trim()
@list.html("") # clear list
@current: 0
if @query.present()
@matches: @matching_completions(@query)
def: @create_item("Add <em>" + @query + "</em>")
def.mouseover(@select_index <- this, 0)
for option, i in @matches
item: @create_item(@highlight(option, @query))
item.mouseover(@select_index <- this, i + 1)
@matches.unshift(@query)
@select_index(0)
else
@query: null
select_index: (index) ->
items: @list.find("li")
items.removeClass("auto-focus")
items.filter(":eq(${index})").addClass("auto-focus")
@current: index
navigate_down: ->
next: @current + 1
next: 0 if next >= @matches.length
@select_index(next)
navigate_up: ->
next: @current - 1
next: @matches.length - 1 if next < 0
@select_index(next)
create_item: (text, highlight) ->
item: $(document.createElement("li"))
item.click =>
@multiselect.add_and_reset()
@search()
@input.focus()
item.html(text)
@list.append(item)
item
value: ->
@matches[@current]
highlight: (text, highlight) ->
reg: "(${RegExp.escape(highlight)})"
text.replace(new RegExp(reg, "gi"), '<em>$1</em>')
matching_completions: (text) ->
reg: new RegExp(RegExp.escape(text), "i")
count: 0
$.grep @completions, (c) =>
return false if count >= @multiselect.options.max_complete_results
return false if $.inArray(c, @multiselect.values) > -1
if c.match(reg)
count++
true
else
false
# Hook jQuery extension
$.fn.multiselect: (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
entitizeHTML: -> return this.replace(/</g,'<').replace(/>/g,'>')
unentitizeHTML: -> return this.replace(/</g,'<').replace(/>/g,'>')
blank: -> return this.trim().length == 0
present: -> return not @blank()
};
RegExp.escape: (str) ->
String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
wilkerlucio/jquery-multiselect
|
c274a275c7aa02ee883fb2ff72d41499f74477ae
|
more names for example completion
|
diff --git a/examples/index.html b/examples/index.html
index e75a0e1..c706a96 100644
--- a/examples/index.html
+++ b/examples/index.html
@@ -1,18 +1,42 @@
<!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" xml:lang="en">
<head>
<title>JqueryMultiSelect Example</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="../css/jquery.multiselect.css" media="all">
<script type="text/javascript" src="../vendor/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../js/jquery.multiselect.js"></script>
<script type="text/javascript">
+ names = [
+ "Alejandra Pizarnik",
+ "Alicia Partnoy",
+ "Andres Rivera",
+ "Antonio Porchia",
+ "Arturo Andres Roig",
+ "Felipe Pigna",
+ "Gustavo Nielsen",
+ "Hector German Oesterheld",
+ "Juan Carlos Portantiero",
+ "Juan L. Ortiz",
+ "Manuel Mujica Lainez",
+ "Manuel Puig",
+ "Mario Rodriguez Cobos",
+ "Olga Orozco",
+ "Osvaldo Tierra",
+ "Ricardo Piglia",
+ "Ricardo Rojas",
+ "Roberto Payro",
+ "Silvina Ocampo",
+ "Victoria Ocampo",
+ "Zuriel Barron"
+ ]
+
$(function() {
- $("#sample-tags").multiselect({completions: ['Aaran', 'Matt', 'Wilker']});
+ $("#sample-tags").multiselect({completions: names});
});
</script>
</head>
<body>
<input type="text" name="tags" id="sample-tags" value="initial,values" />
</body>
</html>
\ No newline at end of file
|
wilkerlucio/jquery-multiselect
|
7363c29f2aab7cf11bf2d0a9e036015d5adda52c
|
prevent default on up and down keys
|
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index c9446d9..ee01531 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,450 +1,452 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ",",
completions: [],
max_complete_results: 5
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
this.parse_value();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
return this.parse_value(1);
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
return this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.add_and_reset();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.prototype.parse_value = function parse_value(min) {
var _a, _b, _c, value, values;
min = (typeof min !== "undefined" && min !== null) ? min : 0;
values = this.input.val().split(this.options.separator);
if (values.length > min) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.present()) {
this.add(value);
}
}
return this.input.val("");
}
};
$.MultiSelect.prototype.add_and_reset = function add_and_reset() {
if (this.autocomplete.value()) {
this.add(this.autocomplete.value());
return this.input.val("");
}
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value, this.values) > -1) {
return null;
}
if (value.blank()) {
return null;
}
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
a.html(value.entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
this.remove(a.data("value"));
return a.remove();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
this.values = $.grep(this.values, function(v) {
return v !== value;
});
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values.join(this.options.separator));
};
// Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
// Selection Helper
// TODO: support IE
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
return [this.input.selectionStart, this.input.selectionEnd];
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
// Resizable Input Helper
$.MultiSelect.ResizableInput = function ResizableInput(element) {
this.input = $(element);
this.create_measurer();
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
return this;
};
$.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
var measurer;
if ($("#__jquery_multiselect_measurer")[0] === undefined) {
measurer = $(document.createElement("div"));
measurer.attr("id", "__jquery_multiselect_measurer");
measurer.css({
position: "absolute",
left: "-1000px",
top: "-1000px"
});
$(document.body).append(measurer);
}
this.measurer = $("#__jquery_multiselect_measurer:first");
return this.measurer.css({
fontSize: this.input.css('font-size'),
fontFamily: this.input.css('font-family')
});
};
$.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
this.measurer.html(this.input.val().entitizeHTML() + 'MM');
return parseInt(this.measurer.css("width"));
};
$.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
return this.input.css("width", this.calculate_width() + "px");
};
// AutoComplete Helper
$.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) {
this.multiselect = multiselect;
this.input = this.multiselect.input;
this.completions = completions;
this.matches = [];
this.create_elements();
this.bind_events();
return this;
};
$.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() {
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect-autocomplete");
this.container.css("width", this.multiselect.container.outerWidth());
this.container.append(this.def);
this.list = $(document.createElement("ul"));
this.list.addClass("feed");
this.container.append(this.list);
return this.multiselect.container.after(this.container);
};
$.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() {
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.multiselect.observer.bind(KEY.UP, (function(__this) {
- var __func = function() {
+ var __func = function(e) {
+ e.preventDefault();
return this.navigate_up();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.multiselect.observer.bind(KEY.DOWN, (function(__this) {
- var __func = function() {
+ var __func = function(e) {
+ e.preventDefault();
return this.navigate_down();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.AutoComplete.prototype.search = function search() {
var _a, _b, def, i, item, option;
if (this.input.val().trim() === this.query) {
return null;
}
// dont do operation if query is same
this.query = this.input.val().trim();
this.list.html("");
// clear list
this.current = 0;
if (this.query.present()) {
this.matches = this.matching_completions(this.query);
def = this.create_item("Add <em>" + this.query + "</em>");
def.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [0])));
_a = this.matches;
for (i = 0, _b = _a.length; i < _b; i++) {
option = _a[i];
item = this.create_item(this.highlight(option, this.query));
item.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [i + 1])));
}
this.matches.unshift(this.query);
return this.select_index(0);
} else {
this.query = null;
return this.query;
}
};
$.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) {
var items;
items = this.list.find("li");
items.removeClass("auto-focus");
items.filter(":eq(" + (index) + ")").addClass("auto-focus");
this.current = index;
return this.current;
};
$.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() {
var next;
next = this.current + 1;
if (next >= this.matches.length) {
next = 0;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() {
var next;
next = this.current - 1;
if (next < 0) {
next = this.matches.length - 1;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) {
var item;
item = $(document.createElement("li"));
item.click((function(__this) {
var __func = function() {
this.multiselect.add_and_reset();
this.search();
return this.input.focus();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
item.html(text);
this.list.append(item);
return item;
};
$.MultiSelect.AutoComplete.prototype.value = function value() {
return this.matches[this.current];
};
$.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) {
var reg;
reg = "(" + (RegExp.escape(highlight)) + ")";
return text.replace(new RegExp(reg, "gi"), '<em>$1</em>');
};
$.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) {
var count, reg;
reg = new RegExp(RegExp.escape(text), "i");
count = 0;
return $.grep(this.completions, (function(__this) {
var __func = function(c) {
if (count >= this.multiselect.options.max_complete_results) {
return false;
}
if ($.inArray(c, this.multiselect.values) > -1) {
return false;
}
if (c.match(reg)) {
count++;
return true;
} else {
return false;
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// Hook jQuery extension
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
blank: function blank() {
return this.trim().length === 0;
},
present: function present() {
return !this.blank();
}
});
RegExp.escape = function escape(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index 28cb1b2..72c1c7f 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,314 +1,314 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
completions: [],
max_complete_results: 5
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
@parse_value()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection: new $.MultiSelect.Selection(@input)
@resizable: new $.MultiSelect.ResizableInput(@input)
@observer: new $.MultiSelect.InputObserver(@input)
@autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
@parse_value(1)
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
e.preventDefault()
@add_and_reset()
parse_value: (min) ->
min ?= 0
values: @input.val().split(@options.separator)
if values.length > min
for value in values
@add value if value.present()
@input.val("")
add_and_reset: ->
if @autocomplete.value()
@add(@autocomplete.value())
@input.val("")
# add new element
add: (value) ->
return if $.inArray(value, @values) > -1
return if value.blank()
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
a.html(value.entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.remove()
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
@values: $.grep @values, (v) -> v != value
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values.join(@options.separator))
# Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
# Selection Helper
# TODO: support IE
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart: begin
@input.selectionEnd: end
set_caret_at_end: ->
@set_caret(@input.value.length)
# Resizable Input Helper
class $.MultiSelect.ResizableInput
constructor: (element) ->
@input: $(element)
@create_measurer()
@input.keypress(@set_width <- this)
@input.keyup(@set_width <- this)
@input.change(@set_width <- this)
create_measurer: ->
if $("#__jquery_multiselect_measurer")[0] == undefined
measurer: $(document.createElement("div"))
measurer.attr("id", "__jquery_multiselect_measurer")
measurer.css {
position: "absolute"
left: "-1000px"
top: "-1000px"
}
$(document.body).append(measurer)
@measurer: $("#__jquery_multiselect_measurer:first")
@measurer.css {
fontSize: @input.css('font-size')
fontFamily: @input.css('font-family')
}
calculate_width: ->
@measurer.html(@input.val().entitizeHTML() + 'MM')
parseInt(@measurer.css("width"))
set_width: ->
@input.css("width", @calculate_width() + "px")
# AutoComplete Helper
class $.MultiSelect.AutoComplete
constructor: (multiselect, completions) ->
@multiselect: multiselect
@input: @multiselect.input
@completions: completions
@matches: []
@create_elements()
@bind_events()
create_elements: ->
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect-autocomplete")
@container.css("width", @multiselect.container.outerWidth())
@container.append(@def)
@list: $(document.createElement("ul"))
@list.addClass("feed")
@container.append(@list)
@multiselect.container.after(@container)
bind_events: ->
@input.keypress(@search <- this)
@input.keyup(@search <- this)
@input.change(@search <- this)
- @multiselect.observer.bind KEY.UP, => @navigate_up()
- @multiselect.observer.bind KEY.DOWN, => @navigate_down()
+ @multiselect.observer.bind KEY.UP, (e) => e.preventDefault(); @navigate_up()
+ @multiselect.observer.bind KEY.DOWN, (e) => e.preventDefault(); @navigate_down()
search: ->
return if @input.val().trim() == @query # dont do operation if query is same
@query: @input.val().trim()
@list.html("") # clear list
@current: 0
if @query.present()
@matches: @matching_completions(@query)
def: @create_item("Add <em>" + @query + "</em>")
def.mouseover(@select_index <- this, 0)
for option, i in @matches
item: @create_item(@highlight(option, @query))
item.mouseover(@select_index <- this, i + 1)
@matches.unshift(@query)
@select_index(0)
else
@query: null
select_index: (index) ->
items: @list.find("li")
items.removeClass("auto-focus")
items.filter(":eq(${index})").addClass("auto-focus")
@current: index
navigate_down: ->
next: @current + 1
next: 0 if next >= @matches.length
@select_index(next)
navigate_up: ->
next: @current - 1
next: @matches.length - 1 if next < 0
@select_index(next)
create_item: (text, highlight) ->
item: $(document.createElement("li"))
item.click =>
@multiselect.add_and_reset()
@search()
@input.focus()
item.html(text)
@list.append(item)
item
value: ->
@matches[@current]
highlight: (text, highlight) ->
reg: "(${RegExp.escape(highlight)})"
text.replace(new RegExp(reg, "gi"), '<em>$1</em>')
matching_completions: (text) ->
reg: new RegExp(RegExp.escape(text), "i")
count: 0
$.grep @completions, (c) =>
return false if count >= @multiselect.options.max_complete_results
return false if $.inArray(c, @multiselect.values) > -1
if c.match(reg)
count++
true
else
false
# Hook jQuery extension
$.fn.multiselect: (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
entitizeHTML: -> return this.replace(/</g,'<').replace(/>/g,'>')
unentitizeHTML: -> return this.replace(/</g,'<').replace(/>/g,'>')
blank: -> return this.trim().length == 0
present: -> return not @blank()
};
RegExp.escape: (str) ->
String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
wilkerlucio/jquery-multiselect
|
2457d0e6bb9fd2afc3e19910213e11f9d3c766c6
|
parse initial value of input
|
diff --git a/examples/index.html b/examples/index.html
index 15008ce..e75a0e1 100644
--- a/examples/index.html
+++ b/examples/index.html
@@ -1,18 +1,18 @@
<!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" xml:lang="en">
<head>
<title>JqueryMultiSelect Example</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="../css/jquery.multiselect.css" media="all">
<script type="text/javascript" src="../vendor/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../js/jquery.multiselect.js"></script>
<script type="text/javascript">
$(function() {
$("#sample-tags").multiselect({completions: ['Aaran', 'Matt', 'Wilker']});
});
</script>
</head>
<body>
- <input type="text" name="tags" id="sample-tags" />
+ <input type="text" name="tags" id="sample-tags" value="initial,values" />
</body>
</html>
\ No newline at end of file
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index 83c8302..c9446d9 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,445 +1,450 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ",",
completions: [],
max_complete_results: 5
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
+ this.parse_value();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
- var _a, _b, _c, value, values;
- values = this.input.val().split(this.options.separator);
- if (values.length > 1) {
- _b = values;
- for (_a = 0, _c = _b.length; _a < _c; _a++) {
- value = _b[_a];
- if (value.length > 0) {
- this.add(value);
- }
- }
- return this.input.val("");
- }
+ return this.parse_value(1);
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
return this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
e.preventDefault();
return this.add_and_reset();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
+ $.MultiSelect.prototype.parse_value = function parse_value(min) {
+ var _a, _b, _c, value, values;
+ min = (typeof min !== "undefined" && min !== null) ? min : 0;
+ values = this.input.val().split(this.options.separator);
+ if (values.length > min) {
+ _b = values;
+ for (_a = 0, _c = _b.length; _a < _c; _a++) {
+ value = _b[_a];
+ if (value.present()) {
+ this.add(value);
+ }
+ }
+ return this.input.val("");
+ }
+ };
$.MultiSelect.prototype.add_and_reset = function add_and_reset() {
if (this.autocomplete.value()) {
this.add(this.autocomplete.value());
return this.input.val("");
}
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value, this.values) > -1) {
return null;
}
if (value.blank()) {
return null;
}
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
a.html(value.entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
this.remove(a.data("value"));
return a.remove();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
this.values = $.grep(this.values, function(v) {
return v !== value;
});
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values.join(this.options.separator));
};
// Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
// Selection Helper
// TODO: support IE
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
return [this.input.selectionStart, this.input.selectionEnd];
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
// Resizable Input Helper
$.MultiSelect.ResizableInput = function ResizableInput(element) {
this.input = $(element);
this.create_measurer();
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
return this;
};
$.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
var measurer;
if ($("#__jquery_multiselect_measurer")[0] === undefined) {
measurer = $(document.createElement("div"));
measurer.attr("id", "__jquery_multiselect_measurer");
measurer.css({
position: "absolute",
left: "-1000px",
top: "-1000px"
});
$(document.body).append(measurer);
}
this.measurer = $("#__jquery_multiselect_measurer:first");
return this.measurer.css({
fontSize: this.input.css('font-size'),
fontFamily: this.input.css('font-family')
});
};
$.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
this.measurer.html(this.input.val().entitizeHTML() + 'MM');
return parseInt(this.measurer.css("width"));
};
$.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
return this.input.css("width", this.calculate_width() + "px");
};
// AutoComplete Helper
$.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) {
this.multiselect = multiselect;
this.input = this.multiselect.input;
this.completions = completions;
this.matches = [];
this.create_elements();
this.bind_events();
return this;
};
$.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() {
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect-autocomplete");
this.container.css("width", this.multiselect.container.outerWidth());
this.container.append(this.def);
this.list = $(document.createElement("ul"));
this.list.addClass("feed");
this.container.append(this.list);
return this.multiselect.container.after(this.container);
};
$.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() {
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.search, this, [])));
this.multiselect.observer.bind(KEY.UP, (function(__this) {
var __func = function() {
return this.navigate_up();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
return this.multiselect.observer.bind(KEY.DOWN, (function(__this) {
var __func = function() {
return this.navigate_down();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
$.MultiSelect.AutoComplete.prototype.search = function search() {
var _a, _b, def, i, item, option;
if (this.input.val().trim() === this.query) {
return null;
}
// dont do operation if query is same
this.query = this.input.val().trim();
this.list.html("");
// clear list
this.current = 0;
if (this.query.present()) {
this.matches = this.matching_completions(this.query);
def = this.create_item("Add <em>" + this.query + "</em>");
def.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [0])));
_a = this.matches;
for (i = 0, _b = _a.length; i < _b; i++) {
option = _a[i];
item = this.create_item(this.highlight(option, this.query));
item.mouseover((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.select_index, this, [i + 1])));
}
this.matches.unshift(this.query);
return this.select_index(0);
} else {
this.query = null;
return this.query;
}
};
$.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) {
var items;
items = this.list.find("li");
items.removeClass("auto-focus");
items.filter(":eq(" + (index) + ")").addClass("auto-focus");
this.current = index;
return this.current;
};
$.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() {
var next;
next = this.current + 1;
if (next >= this.matches.length) {
next = 0;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() {
var next;
next = this.current - 1;
if (next < 0) {
next = this.matches.length - 1;
}
return this.select_index(next);
};
$.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) {
var item;
item = $(document.createElement("li"));
item.click((function(__this) {
var __func = function() {
this.multiselect.add_and_reset();
this.search();
return this.input.focus();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
item.html(text);
this.list.append(item);
return item;
};
$.MultiSelect.AutoComplete.prototype.value = function value() {
return this.matches[this.current];
};
$.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) {
var reg;
reg = "(" + (RegExp.escape(highlight)) + ")";
return text.replace(new RegExp(reg, "gi"), '<em>$1</em>');
};
$.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) {
var count, reg;
reg = new RegExp(RegExp.escape(text), "i");
count = 0;
return $.grep(this.completions, (function(__this) {
var __func = function(c) {
if (count >= this.multiselect.options.max_complete_results) {
return false;
}
if ($.inArray(c, this.multiselect.values) > -1) {
return false;
}
if (c.match(reg)) {
count++;
return true;
} else {
return false;
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// Hook jQuery extension
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
blank: function blank() {
return this.trim().length === 0;
},
present: function present() {
return !this.blank();
}
});
RegExp.escape = function escape(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index b63a8a7..28cb1b2 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,309 +1,314 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
completions: [],
max_complete_results: 5
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
+ @parse_value()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection: new $.MultiSelect.Selection(@input)
@resizable: new $.MultiSelect.ResizableInput(@input)
@observer: new $.MultiSelect.InputObserver(@input)
@autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
- values: @input.val().split(@options.separator)
-
- if values.length > 1
- for value in values
- @add value if value.length > 0
-
- @input.val("")
+ @parse_value(1)
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
e.preventDefault()
@add_and_reset()
+ parse_value: (min) ->
+ min ?= 0
+ values: @input.val().split(@options.separator)
+
+ if values.length > min
+ for value in values
+ @add value if value.present()
+
+ @input.val("")
+
add_and_reset: ->
if @autocomplete.value()
@add(@autocomplete.value())
@input.val("")
# add new element
add: (value) ->
return if $.inArray(value, @values) > -1
return if value.blank()
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
a.html(value.entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.remove()
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
@values: $.grep @values, (v) -> v != value
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values.join(@options.separator))
# Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
# Selection Helper
# TODO: support IE
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart: begin
@input.selectionEnd: end
set_caret_at_end: ->
@set_caret(@input.value.length)
# Resizable Input Helper
class $.MultiSelect.ResizableInput
constructor: (element) ->
@input: $(element)
@create_measurer()
@input.keypress(@set_width <- this)
@input.keyup(@set_width <- this)
@input.change(@set_width <- this)
create_measurer: ->
if $("#__jquery_multiselect_measurer")[0] == undefined
measurer: $(document.createElement("div"))
measurer.attr("id", "__jquery_multiselect_measurer")
measurer.css {
position: "absolute"
left: "-1000px"
top: "-1000px"
}
$(document.body).append(measurer)
@measurer: $("#__jquery_multiselect_measurer:first")
@measurer.css {
fontSize: @input.css('font-size')
fontFamily: @input.css('font-family')
}
calculate_width: ->
@measurer.html(@input.val().entitizeHTML() + 'MM')
parseInt(@measurer.css("width"))
set_width: ->
@input.css("width", @calculate_width() + "px")
# AutoComplete Helper
class $.MultiSelect.AutoComplete
constructor: (multiselect, completions) ->
@multiselect: multiselect
@input: @multiselect.input
@completions: completions
@matches: []
@create_elements()
@bind_events()
create_elements: ->
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect-autocomplete")
@container.css("width", @multiselect.container.outerWidth())
@container.append(@def)
@list: $(document.createElement("ul"))
@list.addClass("feed")
@container.append(@list)
@multiselect.container.after(@container)
bind_events: ->
@input.keypress(@search <- this)
@input.keyup(@search <- this)
@input.change(@search <- this)
@multiselect.observer.bind KEY.UP, => @navigate_up()
@multiselect.observer.bind KEY.DOWN, => @navigate_down()
search: ->
return if @input.val().trim() == @query # dont do operation if query is same
@query: @input.val().trim()
@list.html("") # clear list
@current: 0
if @query.present()
@matches: @matching_completions(@query)
def: @create_item("Add <em>" + @query + "</em>")
def.mouseover(@select_index <- this, 0)
for option, i in @matches
item: @create_item(@highlight(option, @query))
item.mouseover(@select_index <- this, i + 1)
@matches.unshift(@query)
@select_index(0)
else
@query: null
select_index: (index) ->
items: @list.find("li")
items.removeClass("auto-focus")
items.filter(":eq(${index})").addClass("auto-focus")
@current: index
navigate_down: ->
next: @current + 1
next: 0 if next >= @matches.length
@select_index(next)
navigate_up: ->
next: @current - 1
next: @matches.length - 1 if next < 0
@select_index(next)
create_item: (text, highlight) ->
item: $(document.createElement("li"))
item.click =>
@multiselect.add_and_reset()
@search()
@input.focus()
item.html(text)
@list.append(item)
item
value: ->
@matches[@current]
highlight: (text, highlight) ->
reg: "(${RegExp.escape(highlight)})"
text.replace(new RegExp(reg, "gi"), '<em>$1</em>')
matching_completions: (text) ->
reg: new RegExp(RegExp.escape(text), "i")
count: 0
$.grep @completions, (c) =>
return false if count >= @multiselect.options.max_complete_results
return false if $.inArray(c, @multiselect.values) > -1
if c.match(reg)
count++
true
else
false
# Hook jQuery extension
$.fn.multiselect: (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
entitizeHTML: -> return this.replace(/</g,'<').replace(/>/g,'>')
unentitizeHTML: -> return this.replace(/</g,'<').replace(/>/g,'>')
blank: -> return this.trim().length == 0
present: -> return not @blank()
};
RegExp.escape: (str) ->
String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
wilkerlucio/jquery-multiselect
|
251f9131656be577ccec323d1c98ddfb37aa265c
|
added autocomplete
|
diff --git a/css/jquery.multiselect.css b/css/jquery.multiselect.css
index ebd0c0b..c7e7bab 100644
--- a/css/jquery.multiselect.css
+++ b/css/jquery.multiselect.css
@@ -1,32 +1,32 @@
/* TextboxList CSS */
*:first-child+html div.holder { padding-bottom: 2px; }
* html div.holder { padding-bottom: 2px; } /* ie7 and below */
-div.jquery-multiselect *, div.autocomplete * { font: 11px "Lucida Grande", "Verdana"; }
+div.jquery-multiselect *, div.jquery-multiselect-autocomplete * { font: 11px "Lucida Grande", "Verdana"; }
/* DIV holder */
div.jquery-multiselect { width: 500px; margin: 0; border: 1px solid #999; overflow: hidden; height: auto !important; height: 1%; padding: 4px 5px 0; cursor: text;}
div.jquery-multiselect a { float: left; margin: 0 5px 4px 0; }
div.jquery-multiselect a.bit { text-decoration: none; color: black; }
div.jquery-multiselect a.bit:active, div.jquery-multiselect a.bit:focus { outline: none; }
div.jquery-multiselect a.bit-box { -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; border: 1px solid #CAD8F3; background: #DEE7F8; padding: 1px 5px 2px; padding-right: 15px; position: relative; cursor: default; }
div.jquery-multiselect a.bit-box-focus { border-color: #598BEC; background: #598BEC; color: #fff; }
div.jquery-multiselect a.bit-hover { background: #BBCEF1; border: 1px solid #6D95E0; }
div.jquery-multiselect a.bit-box a.closebutton { position: absolute; right: 0; top: 5px; display: block; width: 7px; height: 7px; font-size: 1px; background: url('../images/close.gif'); cursor: pointer; }
div.jquery-multiselect a.bit-box a.closebutton:hover { background-position: 7px; }
div.jquery-multiselect a.bit-box a.closebutton:active { outline: none }
div.jquery-multiselect a.bit-input input { width: 150px; margin: 0; border: none; outline: 0; padding: 3px 0 2px; } /* no left/right padding here please */
div.jquery-multiselect a.bit-box-focus a.closebutton, div.jquery-multiselect a.bit-box-focus a.closebutton:hover { background-position: bottom; }
/* Autocompleter CSS */
-div.autocomplete { display: none; position: absolute; width: 512px; background: #eee; }
-div.autocomplete .default { padding: 5px 7px; border: 1px solid #ccc; border-width: 0 1px 1px; }
-div.autocomplete ul { display: none; margin: 0; padding: 0; overflow: auto; }
-div.autocomplete ul li { padding: 5px 12px; z-index: 1000; cursor: pointer; margin: 0; list-style-type: none; border: 1px solid #ccc; border-width: 0 1px 1px; }
-div.autocomplete ul li em { font-weight: bold; font-style: normal; background: #ccc; }
-div.autocomplete ul li.auto-focus { background: #4173CC; color: #fff; }
-div.autocomplete ul li.auto-focus em { background: none; }
+div.jquery-multiselect-autocomplete { position: absolute; width: 512px; background: #eee; }
+div.jquery-multiselect-autocomplete .default { padding: 5px 7px; border: 1px solid #ccc; border-width: 0 1px 1px; }
+div.jquery-multiselect-autocomplete ul { margin: 0; padding: 0; overflow: auto; }
+div.jquery-multiselect-autocomplete ul li { padding: 5px 12px; z-index: 1000; cursor: pointer; margin: 0; list-style-type: none; border: 1px solid #ccc; border-width: 0 1px 1px; }
+div.jquery-multiselect-autocomplete ul li em { font-weight: bold; font-style: normal; background: #ccc; }
+div.jquery-multiselect-autocomplete ul li.auto-focus { background: #4173CC; color: #fff; }
+div.jquery-multiselect-autocomplete ul li.auto-focus em { background: none; }
input.inputMessage { color: #ccc; font-size: 11px; }
/* Mine */
diff --git a/examples/index.html b/examples/index.html
index 3c58a52..15008ce 100644
--- a/examples/index.html
+++ b/examples/index.html
@@ -1,18 +1,18 @@
<!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" xml:lang="en">
<head>
<title>JqueryMultiSelect Example</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="../css/jquery.multiselect.css" media="all">
<script type="text/javascript" src="../vendor/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../js/jquery.multiselect.js"></script>
<script type="text/javascript">
$(function() {
- $("#sample-tags").multiselect();
+ $("#sample-tags").multiselect({completions: ['Aaran', 'Matt', 'Wilker']});
});
</script>
</head>
<body>
<input type="text" name="tags" id="sample-tags" />
</body>
</html>
\ No newline at end of file
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index 3bd3cac..83c8302 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,265 +1,445 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
- separator: ","
+ separator: ",",
+ completions: [],
+ max_complete_results: 5
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
+ this.autocomplete = new $.MultiSelect.AutoComplete(this, this.options.completions);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
var _a, _b, _c, value, values;
values = this.input.val().split(this.options.separator);
if (values.length > 1) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.length > 0) {
this.add(value);
}
}
return this.input.val("");
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
return this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
e.preventDefault();
- this.add(this.input.val());
- return this.input.val("");
+ return this.add_and_reset();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
+ $.MultiSelect.prototype.add_and_reset = function add_and_reset() {
+ if (this.autocomplete.value()) {
+ this.add(this.autocomplete.value());
+ return this.input.val("");
+ }
+ };
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value, this.values) > -1) {
return null;
}
+ if (value.blank()) {
+ return null;
+ }
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
a.html(value.entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
this.remove(a.data("value"));
return a.remove();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
- console.log(value);
this.values = $.grep(this.values, function(v) {
return v !== value;
});
- console.log(this.values);
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values.join(this.options.separator));
};
// Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
// Selection Helper
// TODO: support IE
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
return [this.input.selectionStart, this.input.selectionEnd];
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
// Resizable Input Helper
$.MultiSelect.ResizableInput = function ResizableInput(element) {
this.input = $(element);
this.create_measurer();
this.input.keypress((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.keyup((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
this.input.change((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.set_width, this, [])));
return this;
};
$.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
var measurer;
if ($("#__jquery_multiselect_measurer")[0] === undefined) {
measurer = $(document.createElement("div"));
measurer.attr("id", "__jquery_multiselect_measurer");
measurer.css({
position: "absolute",
left: "-1000px",
top: "-1000px"
});
$(document.body).append(measurer);
}
this.measurer = $("#__jquery_multiselect_measurer:first");
return this.measurer.css({
fontSize: this.input.css('font-size'),
fontFamily: this.input.css('font-family')
});
};
$.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
this.measurer.html(this.input.val().entitizeHTML() + 'MM');
return parseInt(this.measurer.css("width"));
};
$.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
return this.input.css("width", this.calculate_width() + "px");
};
+ // AutoComplete Helper
+ $.MultiSelect.AutoComplete = function AutoComplete(multiselect, completions) {
+ this.multiselect = multiselect;
+ this.input = this.multiselect.input;
+ this.completions = completions;
+ this.matches = [];
+ this.create_elements();
+ this.bind_events();
+ return this;
+ };
+ $.MultiSelect.AutoComplete.prototype.create_elements = function create_elements() {
+ this.container = $(document.createElement("div"));
+ this.container.addClass("jquery-multiselect-autocomplete");
+ this.container.css("width", this.multiselect.container.outerWidth());
+ this.container.append(this.def);
+ this.list = $(document.createElement("ul"));
+ this.list.addClass("feed");
+ this.container.append(this.list);
+ return this.multiselect.container.after(this.container);
+ };
+ $.MultiSelect.AutoComplete.prototype.bind_events = function bind_events() {
+ this.input.keypress((function(func, obj, args) {
+ return function() {
+ return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
+ };
+ }(this.search, this, [])));
+ this.input.keyup((function(func, obj, args) {
+ return function() {
+ return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
+ };
+ }(this.search, this, [])));
+ this.input.change((function(func, obj, args) {
+ return function() {
+ return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
+ };
+ }(this.search, this, [])));
+ this.multiselect.observer.bind(KEY.UP, (function(__this) {
+ var __func = function() {
+ return this.navigate_up();
+ };
+ return (function() {
+ return __func.apply(__this, arguments);
+ });
+ })(this));
+ return this.multiselect.observer.bind(KEY.DOWN, (function(__this) {
+ var __func = function() {
+ return this.navigate_down();
+ };
+ return (function() {
+ return __func.apply(__this, arguments);
+ });
+ })(this));
+ };
+ $.MultiSelect.AutoComplete.prototype.search = function search() {
+ var _a, _b, def, i, item, option;
+ if (this.input.val().trim() === this.query) {
+ return null;
+ }
+ // dont do operation if query is same
+ this.query = this.input.val().trim();
+ this.list.html("");
+ // clear list
+ this.current = 0;
+ if (this.query.present()) {
+ this.matches = this.matching_completions(this.query);
+ def = this.create_item("Add <em>" + this.query + "</em>");
+ def.mouseover((function(func, obj, args) {
+ return function() {
+ return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
+ };
+ }(this.select_index, this, [0])));
+ _a = this.matches;
+ for (i = 0, _b = _a.length; i < _b; i++) {
+ option = _a[i];
+ item = this.create_item(this.highlight(option, this.query));
+ item.mouseover((function(func, obj, args) {
+ return function() {
+ return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
+ };
+ }(this.select_index, this, [i + 1])));
+ }
+ this.matches.unshift(this.query);
+ return this.select_index(0);
+ } else {
+ this.query = null;
+ return this.query;
+ }
+ };
+ $.MultiSelect.AutoComplete.prototype.select_index = function select_index(index) {
+ var items;
+ items = this.list.find("li");
+ items.removeClass("auto-focus");
+ items.filter(":eq(" + (index) + ")").addClass("auto-focus");
+ this.current = index;
+ return this.current;
+ };
+ $.MultiSelect.AutoComplete.prototype.navigate_down = function navigate_down() {
+ var next;
+ next = this.current + 1;
+ if (next >= this.matches.length) {
+ next = 0;
+ }
+ return this.select_index(next);
+ };
+ $.MultiSelect.AutoComplete.prototype.navigate_up = function navigate_up() {
+ var next;
+ next = this.current - 1;
+ if (next < 0) {
+ next = this.matches.length - 1;
+ }
+ return this.select_index(next);
+ };
+ $.MultiSelect.AutoComplete.prototype.create_item = function create_item(text, highlight) {
+ var item;
+ item = $(document.createElement("li"));
+ item.click((function(__this) {
+ var __func = function() {
+ this.multiselect.add_and_reset();
+ this.search();
+ return this.input.focus();
+ };
+ return (function() {
+ return __func.apply(__this, arguments);
+ });
+ })(this));
+ item.html(text);
+ this.list.append(item);
+ return item;
+ };
+ $.MultiSelect.AutoComplete.prototype.value = function value() {
+ return this.matches[this.current];
+ };
+ $.MultiSelect.AutoComplete.prototype.highlight = function highlight(text, highlight) {
+ var reg;
+ reg = "(" + (RegExp.escape(highlight)) + ")";
+ return text.replace(new RegExp(reg, "gi"), '<em>$1</em>');
+ };
+ $.MultiSelect.AutoComplete.prototype.matching_completions = function matching_completions(text) {
+ var count, reg;
+ reg = new RegExp(RegExp.escape(text), "i");
+ count = 0;
+ return $.grep(this.completions, (function(__this) {
+ var __func = function(c) {
+ if (count >= this.multiselect.options.max_complete_results) {
+ return false;
+ }
+ if ($.inArray(c, this.multiselect.values) > -1) {
+ return false;
+ }
+ if (c.match(reg)) {
+ count++;
+ return true;
+ } else {
+ return false;
+ }
+ };
+ return (function() {
+ return __func.apply(__this, arguments);
+ });
+ })(this));
+ };
+ // Hook jQuery extension
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
+ },
+ blank: function blank() {
+ return this.trim().length === 0;
+ },
+ present: function present() {
+ return !this.blank();
}
-});
\ No newline at end of file
+});
+RegExp.escape = function escape(str) {
+ return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
+};
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index b7feeed..b63a8a7 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,198 +1,309 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
+ completions: [],
+ max_complete_results: 5
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
- @selection = new $.MultiSelect.Selection(@input)
- @resizable = new $.MultiSelect.ResizableInput(@input)
- @observer = new $.MultiSelect.InputObserver(@input)
+ @selection: new $.MultiSelect.Selection(@input)
+ @resizable: new $.MultiSelect.ResizableInput(@input)
+ @observer: new $.MultiSelect.InputObserver(@input)
+ @autocomplete: new $.MultiSelect.AutoComplete(this, @options.completions)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
- values = @input.val().split(@options.separator)
+ values: @input.val().split(@options.separator)
if values.length > 1
for value in values
@add value if value.length > 0
@input.val("")
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
e.preventDefault()
- @add(@input.val())
+ @add_and_reset()
+
+ add_and_reset: ->
+ if @autocomplete.value()
+ @add(@autocomplete.value())
@input.val("")
# add new element
add: (value) ->
return if $.inArray(value, @values) > -1
+ return if value.blank()
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
a.html(value.entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.remove()
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
- console.log(value)
- @values = $.grep @values, (v) -> v != value
- console.log(@values)
+ @values: $.grep @values, (v) -> v != value
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values.join(@options.separator))
# Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
# Selection Helper
# TODO: support IE
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
- @input.selectionStart = begin
- @input.selectionEnd = end
+ @input.selectionStart: begin
+ @input.selectionEnd: end
set_caret_at_end: ->
@set_caret(@input.value.length)
# Resizable Input Helper
class $.MultiSelect.ResizableInput
constructor: (element) ->
@input: $(element)
@create_measurer()
@input.keypress(@set_width <- this)
@input.keyup(@set_width <- this)
@input.change(@set_width <- this)
create_measurer: ->
if $("#__jquery_multiselect_measurer")[0] == undefined
measurer: $(document.createElement("div"))
measurer.attr("id", "__jquery_multiselect_measurer")
measurer.css {
position: "absolute"
left: "-1000px"
top: "-1000px"
}
$(document.body).append(measurer)
@measurer: $("#__jquery_multiselect_measurer:first")
@measurer.css {
fontSize: @input.css('font-size')
fontFamily: @input.css('font-family')
}
calculate_width: ->
@measurer.html(@input.val().entitizeHTML() + 'MM')
parseInt(@measurer.css("width"))
set_width: ->
@input.css("width", @calculate_width() + "px")
- $.fn.multiselect = (options) ->
+ # AutoComplete Helper
+ class $.MultiSelect.AutoComplete
+ constructor: (multiselect, completions) ->
+ @multiselect: multiselect
+ @input: @multiselect.input
+ @completions: completions
+ @matches: []
+ @create_elements()
+ @bind_events()
+
+ create_elements: ->
+ @container: $(document.createElement("div"))
+ @container.addClass("jquery-multiselect-autocomplete")
+ @container.css("width", @multiselect.container.outerWidth())
+
+ @container.append(@def)
+
+ @list: $(document.createElement("ul"))
+ @list.addClass("feed")
+
+ @container.append(@list)
+ @multiselect.container.after(@container)
+
+ bind_events: ->
+ @input.keypress(@search <- this)
+ @input.keyup(@search <- this)
+ @input.change(@search <- this)
+ @multiselect.observer.bind KEY.UP, => @navigate_up()
+ @multiselect.observer.bind KEY.DOWN, => @navigate_down()
+
+ search: ->
+ return if @input.val().trim() == @query # dont do operation if query is same
+
+ @query: @input.val().trim()
+ @list.html("") # clear list
+ @current: 0
+
+ if @query.present()
+ @matches: @matching_completions(@query)
+
+ def: @create_item("Add <em>" + @query + "</em>")
+ def.mouseover(@select_index <- this, 0)
+
+ for option, i in @matches
+ item: @create_item(@highlight(option, @query))
+ item.mouseover(@select_index <- this, i + 1)
+
+ @matches.unshift(@query)
+ @select_index(0)
+ else
+ @query: null
+
+ select_index: (index) ->
+ items: @list.find("li")
+ items.removeClass("auto-focus")
+ items.filter(":eq(${index})").addClass("auto-focus")
+
+ @current: index
+
+ navigate_down: ->
+ next: @current + 1
+ next: 0 if next >= @matches.length
+ @select_index(next)
+
+ navigate_up: ->
+ next: @current - 1
+ next: @matches.length - 1 if next < 0
+ @select_index(next)
+
+ create_item: (text, highlight) ->
+ item: $(document.createElement("li"))
+ item.click =>
+ @multiselect.add_and_reset()
+ @search()
+ @input.focus()
+ item.html(text)
+ @list.append(item)
+ item
+
+ value: ->
+ @matches[@current]
+
+ highlight: (text, highlight) ->
+ reg: "(${RegExp.escape(highlight)})"
+ text.replace(new RegExp(reg, "gi"), '<em>$1</em>')
+
+ matching_completions: (text) ->
+ reg: new RegExp(RegExp.escape(text), "i")
+ count: 0
+ $.grep @completions, (c) =>
+ return false if count >= @multiselect.options.max_complete_results
+ return false if $.inArray(c, @multiselect.values) > -1
+
+ if c.match(reg)
+ count++
+ true
+ else
+ false
+
+ # Hook jQuery extension
+ $.fn.multiselect: (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
entitizeHTML: -> return this.replace(/</g,'<').replace(/>/g,'>')
unentitizeHTML: -> return this.replace(/</g,'<').replace(/>/g,'>')
-};
\ No newline at end of file
+ blank: -> return this.trim().length == 0
+ present: -> return not @blank()
+};
+
+RegExp.escape: (str) ->
+ String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
|
wilkerlucio/jquery-multiselect
|
ba6789b576bf438523fa5a4d81a1b71b41351d64
|
added resizable input and few comments
|
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index c030b8f..3bd3cac 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,215 +1,265 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ","
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
+ this.resizable = new $.MultiSelect.ResizableInput(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
var _a, _b, _c, value, values;
values = this.input.val().split(this.options.separator);
if (values.length > 1) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.length > 0) {
this.add(value);
}
}
return this.input.val("");
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
return this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
e.preventDefault();
this.add(this.input.val());
return this.input.val("");
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value, this.values) > -1) {
return null;
}
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
a.html(value.entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
this.remove(a.data("value"));
return a.remove();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
console.log(value);
this.values = $.grep(this.values, function(v) {
return v !== value;
});
console.log(this.values);
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values.join(this.options.separator));
};
+ // Input Observer Helper
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
+ // Selection Helper
+ // TODO: support IE
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
return [this.input.selectionStart, this.input.selectionEnd];
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
+ // Resizable Input Helper
+ $.MultiSelect.ResizableInput = function ResizableInput(element) {
+ this.input = $(element);
+ this.create_measurer();
+ this.input.keypress((function(func, obj, args) {
+ return function() {
+ return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
+ };
+ }(this.set_width, this, [])));
+ this.input.keyup((function(func, obj, args) {
+ return function() {
+ return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
+ };
+ }(this.set_width, this, [])));
+ this.input.change((function(func, obj, args) {
+ return function() {
+ return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
+ };
+ }(this.set_width, this, [])));
+ return this;
+ };
+ $.MultiSelect.ResizableInput.prototype.create_measurer = function create_measurer() {
+ var measurer;
+ if ($("#__jquery_multiselect_measurer")[0] === undefined) {
+ measurer = $(document.createElement("div"));
+ measurer.attr("id", "__jquery_multiselect_measurer");
+ measurer.css({
+ position: "absolute",
+ left: "-1000px",
+ top: "-1000px"
+ });
+ $(document.body).append(measurer);
+ }
+ this.measurer = $("#__jquery_multiselect_measurer:first");
+ return this.measurer.css({
+ fontSize: this.input.css('font-size'),
+ fontFamily: this.input.css('font-family')
+ });
+ };
+ $.MultiSelect.ResizableInput.prototype.calculate_width = function calculate_width() {
+ this.measurer.html(this.input.val().entitizeHTML() + 'MM');
+ return parseInt(this.measurer.css("width"));
+ };
+ $.MultiSelect.ResizableInput.prototype.set_width = function set_width() {
+ return this.input.css("width", this.calculate_width() + "px");
+ };
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
})(jQuery);
$.extend(String.prototype, {
entitizeHTML: function entitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
},
unentitizeHTML: function unentitizeHTML() {
return this.replace(/</g, '<').replace(/>/g, '>');
}
});
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index ba9325e..b7feeed 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,160 +1,198 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection = new $.MultiSelect.Selection(@input)
+ @resizable = new $.MultiSelect.ResizableInput(@input)
@observer = new $.MultiSelect.InputObserver(@input)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
values = @input.val().split(@options.separator)
if values.length > 1
for value in values
@add value if value.length > 0
@input.val("")
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
e.preventDefault()
@add(@input.val())
@input.val("")
# add new element
add: (value) ->
return if $.inArray(value, @values) > -1
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
a.html(value.entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.remove()
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
console.log(value)
@values = $.grep @values, (v) -> v != value
console.log(@values)
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values.join(@options.separator))
-
+
+ # Input Observer Helper
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
+ # Selection Helper
+ # TODO: support IE
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart = begin
@input.selectionEnd = end
set_caret_at_end: ->
@set_caret(@input.value.length)
+ # Resizable Input Helper
+ class $.MultiSelect.ResizableInput
+ constructor: (element) ->
+ @input: $(element)
+ @create_measurer()
+ @input.keypress(@set_width <- this)
+ @input.keyup(@set_width <- this)
+ @input.change(@set_width <- this)
+
+ create_measurer: ->
+ if $("#__jquery_multiselect_measurer")[0] == undefined
+ measurer: $(document.createElement("div"))
+ measurer.attr("id", "__jquery_multiselect_measurer")
+ measurer.css {
+ position: "absolute"
+ left: "-1000px"
+ top: "-1000px"
+ }
+
+ $(document.body).append(measurer)
+
+ @measurer: $("#__jquery_multiselect_measurer:first")
+ @measurer.css {
+ fontSize: @input.css('font-size')
+ fontFamily: @input.css('font-family')
+ }
+
+ calculate_width: ->
+ @measurer.html(@input.val().entitizeHTML() + 'MM')
+ parseInt(@measurer.css("width"))
+
+ set_width: ->
+ @input.css("width", @calculate_width() + "px")
+
$.fn.multiselect = (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
)(jQuery)
$.extend String.prototype, {
entitizeHTML: -> return this.replace(/</g,'<').replace(/>/g,'>')
unentitizeHTML: -> return this.replace(/</g,'<').replace(/>/g,'>')
};
\ No newline at end of file
|
wilkerlucio/jquery-multiselect
|
226ffc2e93718d3438b7e5132920a3c9c42f430a
|
entitizing html
|
diff --git a/js/jquery.multiselect.js b/js/jquery.multiselect.js
index cc9427b..c030b8f 100644
--- a/js/jquery.multiselect.js
+++ b/js/jquery.multiselect.js
@@ -1,207 +1,215 @@
// Copyright (c) 2010 Wilker Lúcio
//
// 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.
(function($) {
var KEY;
KEY = {
TAB: 9,
RETURN: 13,
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
COLON: 188,
DOT: 190
};
$.MultiSelect = function MultiSelect(element, options) {
this.options = {
separator: ","
};
$.extend(this.options, options || {});
this.values = [];
this.input = $(element);
this.initialize_elements();
this.initialize_events();
return this;
};
$.MultiSelect.prototype.initialize_elements = function initialize_elements() {
// hidden input to hold real value
this.hidden = $(document.createElement("input"));
this.hidden.attr("name", this.input.attr("name"));
this.hidden.attr("type", "hidden");
this.input.removeAttr("name");
this.container = $(document.createElement("div"));
this.container.addClass("jquery-multiselect");
this.input_wrapper = $(document.createElement("a"));
this.input_wrapper.addClass("bit-input");
this.input.replaceWith(this.container);
this.container.append(this.input_wrapper);
this.input_wrapper.append(this.input);
return this.container.before(this.hidden);
};
$.MultiSelect.prototype.initialize_events = function initialize_events() {
// create helpers
this.selection = new $.MultiSelect.Selection(this.input);
this.observer = new $.MultiSelect.InputObserver(this.input);
// prevent container click to put carret at end
this.input.click((function(__this) {
var __func = function(e) {
return e.stopPropagation();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// create element when place separator or paste
this.input.keyup((function(__this) {
var __func = function() {
var _a, _b, _c, value, values;
values = this.input.val().split(this.options.separator);
if (values.length > 1) {
_b = values;
for (_a = 0, _c = _b.length; _a < _c; _a++) {
value = _b[_a];
if (value.length > 0) {
this.add(value);
}
}
return this.input.val("");
}
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// focus input and set carret at and
this.container.click((function(__this) {
var __func = function() {
this.input.focus();
return this.selection.set_caret_at_end();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
// add element on press TAB or RETURN
return this.observer.bind([KEY.TAB, KEY.RETURN], (function(__this) {
var __func = function(e) {
e.preventDefault();
this.add(this.input.val());
return this.input.val("");
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
};
// add new element
$.MultiSelect.prototype.add = function add(value) {
var a, close;
if ($.inArray(value, this.values) > -1) {
return null;
}
this.values.push(value);
a = $(document.createElement("a"));
a.addClass("bit bit-box");
a.mouseover(function() {
return $(this).addClass("bit-hover");
});
a.mouseout(function() {
return $(this).removeClass("bit-hover");
});
a.data("value", value);
- a.html(value);
+ a.html(value.entitizeHTML());
close = $(document.createElement("a"));
close.addClass("closebutton");
close.click((function(__this) {
var __func = function() {
this.remove(a.data("value"));
return a.remove();
};
return (function() {
return __func.apply(__this, arguments);
});
})(this));
a.append(close);
this.input_wrapper.before(a);
return this.refresh_hidden();
};
$.MultiSelect.prototype.remove = function remove(value) {
console.log(value);
this.values = $.grep(this.values, function(v) {
return v !== value;
});
console.log(this.values);
return this.refresh_hidden();
};
$.MultiSelect.prototype.refresh_hidden = function refresh_hidden() {
return this.hidden.val(this.values.join(this.options.separator));
};
$.MultiSelect.InputObserver = function InputObserver(element) {
this.input = $(element);
this.input.keydown((function(func, obj, args) {
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}(this.handle_keydown, this, [])));
this.events = [];
return this;
};
$.MultiSelect.InputObserver.prototype.bind = function bind(key, callback) {
return this.events.push([key, callback]);
};
$.MultiSelect.InputObserver.prototype.handle_keydown = function handle_keydown(e) {
var _a, _b, _c, _d, _e, callback, event, keys;
_a = []; _c = this.events;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
event = _c[_b];
_a.push((function() {
_e = event;
keys = _e[0];
callback = _e[1];
if (!(keys.push)) {
keys = [keys];
}
if ($.inArray(e.keyCode, keys) > -1) {
return callback(e);
}
}).call(this));
}
return _a;
};
$.MultiSelect.Selection = function Selection(element) {
this.input = $(element)[0];
return this;
};
$.MultiSelect.Selection.prototype.get_caret = function get_caret() {
return [this.input.selectionStart, this.input.selectionEnd];
};
$.MultiSelect.Selection.prototype.set_caret = function set_caret(begin, end) {
end = (typeof end !== "undefined" && end !== null) ? end : begin;
this.input.selectionStart = begin;
this.input.selectionEnd = end;
return this.input.selectionEnd;
};
$.MultiSelect.Selection.prototype.set_caret_at_end = function set_caret_at_end() {
return this.set_caret(this.input.value.length);
};
$.fn.multiselect = function multiselect(options) {
options = (typeof options !== "undefined" && options !== null) ? options : {};
return $(this).each(function() {
return new $.MultiSelect(this, options);
});
};
return $.fn.multiselect;
-})(jQuery);
\ No newline at end of file
+})(jQuery);
+$.extend(String.prototype, {
+ entitizeHTML: function entitizeHTML() {
+ return this.replace(/</g, '<').replace(/>/g, '>');
+ },
+ unentitizeHTML: function unentitizeHTML() {
+ return this.replace(/</g, '<').replace(/>/g, '>');
+ }
+});
\ No newline at end of file
diff --git a/src/jquery.multiselect.coffee b/src/jquery.multiselect.coffee
index 3606767..ba9325e 100644
--- a/src/jquery.multiselect.coffee
+++ b/src/jquery.multiselect.coffee
@@ -1,155 +1,160 @@
# Copyright (c) 2010 Wilker Lúcio
#
# 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.
(($) ->
KEY: {
TAB: 9
RETURN: 13
ESCAPE: 27
SPACE: 32
LEFT: 37
UP: 38
RIGHT: 39
DOWN: 40
COLON: 188
DOT: 190
}
class $.MultiSelect
constructor: (element, options) ->
@options: {
separator: ","
}
$.extend(@options, options || {})
@values: []
@input: $(element)
@initialize_elements()
@initialize_events()
initialize_elements: ->
# hidden input to hold real value
@hidden: $(document.createElement("input"))
@hidden.attr("name", @input.attr("name"))
@hidden.attr("type", "hidden")
@input.removeAttr("name")
@container: $(document.createElement("div"))
@container.addClass("jquery-multiselect")
@input_wrapper: $(document.createElement("a"))
@input_wrapper.addClass("bit-input")
@input.replaceWith(@container)
@container.append(@input_wrapper)
@input_wrapper.append(@input)
@container.before(@hidden)
initialize_events: ->
# create helpers
@selection = new $.MultiSelect.Selection(@input)
@observer = new $.MultiSelect.InputObserver(@input)
# prevent container click to put carret at end
@input.click (e) =>
e.stopPropagation()
# create element when place separator or paste
@input.keyup =>
values = @input.val().split(@options.separator)
if values.length > 1
for value in values
@add value if value.length > 0
@input.val("")
# focus input and set carret at and
@container.click =>
@input.focus()
@selection.set_caret_at_end()
# add element on press TAB or RETURN
@observer.bind [KEY.TAB, KEY.RETURN], (e) =>
e.preventDefault()
@add(@input.val())
@input.val("")
# add new element
add: (value) ->
return if $.inArray(value, @values) > -1
@values.push(value)
a: $(document.createElement("a"))
a.addClass("bit bit-box")
a.mouseover -> $(this).addClass("bit-hover")
a.mouseout -> $(this).removeClass("bit-hover")
a.data("value", value)
- a.html(value)
+ a.html(value.entitizeHTML())
close: $(document.createElement("a"))
close.addClass("closebutton")
close.click =>
@remove(a.data("value"))
a.remove()
a.append(close)
@input_wrapper.before(a)
@refresh_hidden()
remove: (value) ->
console.log(value)
@values = $.grep @values, (v) -> v != value
console.log(@values)
@refresh_hidden()
refresh_hidden: ->
@hidden.val(@values.join(@options.separator))
class $.MultiSelect.InputObserver
constructor: (element) ->
@input: $(element)
@input.keydown(@handle_keydown <- this)
@events: []
bind: (key, callback) ->
@events.push([key, callback])
handle_keydown: (e) ->
for event in @events
[keys, callback]: event
keys: [keys] unless keys.push
callback(e) if $.inArray(e.keyCode, keys) > -1
class $.MultiSelect.Selection
constructor: (element) ->
@input: $(element)[0]
get_caret: ->
[@input.selectionStart, @input.selectionEnd]
set_caret: (begin, end) ->
end ?= begin
@input.selectionStart = begin
@input.selectionEnd = end
set_caret_at_end: ->
@set_caret(@input.value.length)
$.fn.multiselect = (options) ->
options ?= {}
$(this).each ->
new $.MultiSelect(this, options)
-)(jQuery)
\ No newline at end of file
+)(jQuery)
+
+$.extend String.prototype, {
+ entitizeHTML: -> return this.replace(/</g,'<').replace(/>/g,'>')
+ unentitizeHTML: -> return this.replace(/</g,'<').replace(/>/g,'>')
+};
\ No newline at end of file
|
rjbs/Dist-Zilla
|
3a2a76568e2236c6d98d5d825620d8241d110be5
|
v6.033
|
diff --git a/Changes b/Changes
index 1504385..7f7d53f 100644
--- a/Changes
+++ b/Changes
@@ -1,516 +1,521 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+6.033 2025-05-01 11:45:18-04:00 America/New_York
+ - when creating a tarball with GNU tar, use --format=ustar to avoid
+ xattrs and other problems sometimes related to macOS (thanks, Graham
+ Knop!)
+
6.032 2024-05-25 12:30:02-04:00 America/New_York
- UploadToCPAN errors will distinguish between "couldn't find password"
and "something went wrong trying to get password"
- UploadToCPAN can now use any Login-type stash for credentials, not
just a PAUSE-class stash
6.031 2023-11-20 19:49:23-05:00 America/New_York
- avoid some warnings on platforms without symlinks; (thanks, reneeb!)
6.030 2023-01-18 21:36:40-05:00 America/New_York
- "dzil new" will use command line options before configuration
- "dzil add" now falls back to %Mint stash options before defaults
(for both of the above: thanks, Graham Knop!)
6.029 2022-11-25 17:02:33-05:00 America/New_York
- update some links to use https instead of http (thanks, Elvin
Aslanov)
- turn on strict and warnings in generated author tests (thanks, Mark
Flickinger)
- use "v1.2.3" for multi-dot versions in "package NAME VERSION" formats
(thanks, Branislav ZahradnÃk)
- fixes to operation on msys (thanks, Paulo Custodio)
- add "main_module" option to MakeMaker (thanks, Tatsuhiko Miyagawa)
- fix authordeps behavior; don't add an object to @INC (thanks, Shoichi
Kaji)
6.028 2022-11-09 10:54:14-05:00 America/New_York
- remove bogus work-in-progress signatures-using commit from 6.027;
that was a bad release! thanks for the heads-up about it to Gianni
"dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
|
rjbs/Dist-Zilla
|
6397315ea038a5df0f67b1330e09265f81652aac
|
use ustar format when using Archive::Tar::Wrapper
|
diff --git a/lib/Dist/Zilla/Dist/Builder.pm b/lib/Dist/Zilla/Dist/Builder.pm
index a58911b..6cedcb6 100644
--- a/lib/Dist/Zilla/Dist/Builder.pm
+++ b/lib/Dist/Zilla/Dist/Builder.pm
@@ -42,845 +42,847 @@ sub from_config {
my $sequence = $class->_load_config({
root => $root,
chrome => $arg->{chrome},
config_class => $arg->{config_class},
_global_stashes => $arg->{_global_stashes},
});
my $self = $sequence->section_named('_')->zilla;
$self->_setup_default_plugins;
return $self;
}
sub _setup_default_plugins {
my ($self) = @_;
unless ($self->plugin_named(':InstallModules')) {
require Dist::Zilla::Plugin::FinderCode;
my $plugin = Dist::Zilla::Plugin::FinderCode->new({
plugin_name => ':InstallModules',
zilla => $self,
style => 'grep',
code => sub {
my ($file, $self) = @_;
local $_ = $file->name;
return 1 if m{\Alib/} and m{\.(pm|pod)$};
return;
},
});
push @{ $self->plugins }, $plugin;
}
unless ($self->plugin_named(':IncModules')) {
require Dist::Zilla::Plugin::FinderCode;
my $plugin = Dist::Zilla::Plugin::FinderCode->new({
plugin_name => ':IncModules',
zilla => $self,
style => 'grep',
code => sub {
my ($file, $self) = @_;
local $_ = $file->name;
return 1 if m{\Ainc/} and m{\.pm$};
return;
},
});
push @{ $self->plugins }, $plugin;
}
unless ($self->plugin_named(':TestFiles')) {
require Dist::Zilla::Plugin::FinderCode;
my $plugin = Dist::Zilla::Plugin::FinderCode->new({
plugin_name => ':TestFiles',
zilla => $self,
style => 'grep',
code => sub { local $_ = $_->name; m{\At/} },
});
push @{ $self->plugins }, $plugin;
}
unless ($self->plugin_named(':ExtraTestFiles')) {
require Dist::Zilla::Plugin::FinderCode;
my $plugin = Dist::Zilla::Plugin::FinderCode->new({
plugin_name => ':ExtraTestFiles',
zilla => $self,
style => 'grep',
code => sub { local $_ = $_->name; m{\Axt/} },
});
push @{ $self->plugins }, $plugin;
}
unless ($self->plugin_named(':ExecFiles')) {
require Dist::Zilla::Plugin::FinderCode;
my $plugin = Dist::Zilla::Plugin::FinderCode->new({
plugin_name => ':ExecFiles',
zilla => $self,
style => 'list',
code => sub {
my $plugins = $_[0]->zilla->plugins_with(-ExecFiles);
my @files = uniq map {; @{ $_->find_files } } @$plugins;
return \@files;
},
});
push @{ $self->plugins }, $plugin;
}
unless ($self->plugin_named(':PerlExecFiles')) {
require Dist::Zilla::Plugin::FinderCode;
my $plugin = Dist::Zilla::Plugin::FinderCode->new({
plugin_name => ':PerlExecFiles',
zilla => $self,
style => 'list',
code => sub {
my $parent_plugin = $self->plugin_named(':ExecFiles');
my @files = grep {
$_->name =~ m{\.pl$}
or $_->content =~ m{^\s*\#\!.*perl\b};
} @{ $parent_plugin->find_files };
return \@files;
},
});
push @{ $self->plugins }, $plugin;
}
unless ($self->plugin_named(':ShareFiles')) {
require Dist::Zilla::Plugin::FinderCode;
my $plugin = Dist::Zilla::Plugin::FinderCode->new({
plugin_name => ':ShareFiles',
zilla => $self,
style => 'list',
code => sub {
my $self = shift;
my $map = $self->zilla->_share_dir_map;
my @files;
if ( $map->{dist} ) {
push @files, grep {; $_->name =~ m{\A\Q$map->{dist}\E/} }
@{ $self->zilla->files };
}
if ( my $mod_map = $map->{module} ) {
for my $mod ( keys %$mod_map ) {
push @files, grep { $_->name =~ m{\A\Q$mod_map->{$mod}\E/} }
@{ $self->zilla->files };
}
}
return \@files;
},
});
push @{ $self->plugins }, $plugin;
}
unless ($self->plugin_named(':MainModule')) {
require Dist::Zilla::Plugin::FinderCode;
my $plugin = Dist::Zilla::Plugin::FinderCode->new({
plugin_name => ':MainModule',
zilla => $self,
style => 'grep',
code => sub {
my ($file, $self) = @_;
local $_ = $file->name;
return 1 if $_ eq $self->zilla->main_module->name;
return;
},
});
push @{ $self->plugins }, $plugin;
}
unless ($self->plugin_named(':AllFiles')) {
require Dist::Zilla::Plugin::FinderCode;
my $plugin = Dist::Zilla::Plugin::FinderCode->new({
plugin_name => ':AllFiles',
zilla => $self,
style => 'grep',
code => sub { return 1 },
});
push @{ $self->plugins }, $plugin;
}
unless ($self->plugin_named(':NoFiles')) {
require Dist::Zilla::Plugin::FinderCode;
my $plugin = Dist::Zilla::Plugin::FinderCode->new({
plugin_name => ':NoFiles',
zilla => $self,
style => 'list',
code => sub { [] },
});
push @{ $self->plugins }, $plugin;
}
}
has _share_dir_map => (
is => 'ro',
isa => HashRef,
init_arg => undef,
lazy => 1,
builder => '_build_share_dir_map',
);
sub _build_share_dir_map {
my ($self) = @_;
my $share_dir_map = {};
for my $plugin (@{ $self->plugins_with(-ShareDir) }) {
next unless my $sub_map = $plugin->share_dir_map;
if ( $sub_map->{dist} ) {
$self->log_fatal("can't install more than one distribution ShareDir")
if $share_dir_map->{dist};
$share_dir_map->{dist} = $sub_map->{dist};
}
if ( my $mod_map = $sub_map->{module} ) {
for my $mod ( keys %$mod_map ) {
$self->log_fatal("can't install more than one ShareDir for $mod")
if $share_dir_map->{module}{$mod};
$share_dir_map->{module}{$mod} = $mod_map->{$mod};
}
}
}
return $share_dir_map;
}
sub _load_config {
my ($class, $arg) = @_;
$arg ||= {};
my $config_class =
$arg->{config_class} ||= 'Dist::Zilla::MVP::Reader::Finder';
require_module($config_class);
$arg->{chrome}->logger->log_debug(
{ prefix => '[DZ] ' },
"reading configuration using $config_class"
);
my $root = $arg->{root};
require Dist::Zilla::MVP::Assembler::Zilla;
require Dist::Zilla::MVP::Section;
my $assembler = Dist::Zilla::MVP::Assembler::Zilla->new({
chrome => $arg->{chrome},
zilla_class => $class,
section_class => 'Dist::Zilla::MVP::Section', # make this DZMA default
});
for ($assembler->sequence->section_named('_')) {
$_->add_value(chrome => $arg->{chrome});
$_->add_value(root => $arg->{root});
$_->add_value(_global_stashes => $arg->{_global_stashes})
if $arg->{_global_stashes};
}
my $seq;
try {
$seq = $config_class->read_config(
$root->child('dist'),
{
assembler => $assembler
},
);
} catch {
die $_ unless try {
$_->isa('Config::MVP::Error')
and $_->ident eq 'package not installed'
};
my $package = $_->package;
my $bundle = $_->section_name =~ m{^@(?!.*/)} ? ' bundle' : '';
die <<"END_DIE";
Required plugin$bundle $package isn't installed.
Run 'dzil authordeps' to see a list of all required plugins.
You can pipe the list to your CPAN client to install or update them:
dzil authordeps --missing | cpanm
END_DIE
};
return $seq;
}
=method build_in
$zilla->build_in($root);
This method builds the distribution in the given directory. If no directory
name is given, it defaults to DistName-Version. If the distribution has
already been built, an exception will be thrown.
=method build
This method just calls C<build_in> with no arguments. It gets you the default
behavior without the weird-looking formulation of C<build_in> with no object
for the preposition!
=cut
sub build { $_[0]->build_in }
sub build_in {
my ($self, $root) = @_;
$self->log_fatal("tried to build with a minter")
if $self->isa('Dist::Zilla::Dist::Minter');
$self->log_fatal("attempted to build " . $self->name . " a second time")
if $self->built_in;
$_->before_build for @{ $self->plugins_with(-BeforeBuild) };
$self->log("beginning to build " . $self->name);
$_->gather_files for @{ $self->plugins_with(-FileGatherer) };
$_->set_file_encodings for @{ $self->plugins_with(-EncodingProvider) };
$_->prune_files for @{ $self->plugins_with(-FilePruner) };
$self->version; # instantiate this lazy attribute now that files are gathered
$_->munge_files for @{ $self->plugins_with(-FileMunger) };
$_->register_prereqs for @{ $self->plugins_with(-PrereqSource) };
$self->prereqs->finalize;
# Barf if someone has already set up a prereqs entry? -- rjbs, 2010-04-13
$self->distmeta->{prereqs} = $self->prereqs->as_string_hash;
$_->setup_installer for @{ $self->plugins_with(-InstallTool) };
$self->_check_dupe_files;
my $build_root = $self->_prep_build_root($root);
$self->log("writing " . $self->name . " in $build_root");
for my $file (@{ $self->files }) {
$self->_write_out_file($file, $build_root);
}
$_->after_build({ build_root => $build_root })
for @{ $self->plugins_with(-AfterBuild) };
$self->built_in($build_root);
}
=attr built_in
This is the L<Path::Tiny>, if any, in which the dist has been built.
=cut
has built_in => (
is => 'rw',
isa => Path,
init_arg => undef,
coerce => 1,
);
=method ensure_built_in
$zilla->ensure_built_in($root);
This method behaves like C<L</build_in>>, but if the dist is already built in
C<$root> (or the default root, if no root is given), no exception is raised.
=method ensure_built
This method just calls C<ensure_built_in> with no arguments. It gets you the
default behavior without the weird-looking formulation of C<ensure_built_in>
with no object for the preposition!
=cut
sub ensure_built {
$_[0]->ensure_built_in;
}
sub ensure_built_in {
my ($self, $root) = @_;
# $root ||= $self->name . q{-} . $self->version;
return $self->built_in if $self->built_in and
(!$root or ($self->built_in eq $root));
Carp::croak("dist is already built, but not in $root") if $self->built_in;
$self->build_in($root);
}
=method dist_basename
my $basename = $zilla->dist_basename;
This method will return the dist's basename (e.g. C<Dist-Name-1.01>.
The basename is used as the top-level directory in the tarball. It
does not include C<-TRIAL>, even if building a trial dist.
=cut
sub dist_basename {
my ($self) = @_;
return join(q{},
$self->name,
'-',
$self->version,
);
}
=method archive_basename
my $basename = $zilla->archive_basename;
This method will return the filename, without the format extension
(e.g. C<Dist-Name-1.01> or C<Dist-Name-1.01-TRIAL>).
=cut
sub archive_basename {
my ($self) = @_;
return join q{},
$self->dist_basename,
( $self->is_trial && $self->version !~ /_/ ? '-TRIAL' : '' ),
;
}
=method archive_filename
my $tarball = $zilla->archive_filename;
This method will return the filename (e.g. C<Dist-Name-1.01.tar.gz>)
of the tarball of this distribution. It will include C<-TRIAL> if building a
trial distribution, unless the version contains an underscore. The tarball
might not exist.
=cut
sub archive_filename {
my ($self) = @_;
return join q{}, $self->archive_basename, '.tar.gz';
}
=method build_archive
$zilla->build_archive;
This method will ensure that the dist has been built, and will then build a
tarball of the build directory in the current directory.
=cut
sub build_archive {
my ($self) = @_;
my $built_in = $self->ensure_built;
my $basedir = path($self->dist_basename);
$_->before_archive for $self->plugins_with(-BeforeArchive)->@*;
for my $builder ($self->plugins_with(-ArchiveBuilder)->@*) {
my $file = $builder->build_archive($self->archive_basename, $built_in, $basedir);
return $file if defined $file;
}
my $method = eval { +require Archive::Tar::Wrapper;
Archive::Tar::Wrapper->VERSION('0.15'); 1 }
? '_build_archive_with_wrapper'
: '_build_archive';
my $archive = $self->$method($built_in, $basedir);
my $file = path($self->archive_filename);
$self->log("writing archive to $file");
$archive->write("$file", 9);
return $file;
}
sub _build_archive {
my ($self, $built_in, $basedir) = @_;
$self->log("building archive with Archive::Tar; install Archive::Tar::Wrapper 0.15 or newer for improved speed");
require Archive::Tar;
my $archive = Archive::Tar->new;
my %seen_dir;
for my $distfile (
sort { length($a->name) <=> length($b->name) } @{ $self->files }
) {
my $in = path($distfile->name)->parent;
unless ($seen_dir{ $in }++) {
$archive->add_data(
$basedir->child($in),
'',
{ type => Archive::Tar::Constant::DIR(), mode => 0755 },
)
}
my $filename = $built_in->child( $distfile->name );
$archive->add_data(
$basedir->child( $distfile->name ),
path($filename)->slurp_raw,
{ mode => (stat $filename)[2] & ~022 },
);
}
return $archive;
}
sub _build_archive_with_wrapper {
my ($self, $built_in, $basedir) = @_;
$self->log("building archive with Archive::Tar::Wrapper");
- my $archive = Archive::Tar::Wrapper->new;
+ my $archive = Archive::Tar::Wrapper->new(
+ tar_gnu_write_options => ['--format=ustar'],
+ );
for my $distfile (
sort { length($a->name) <=> length($b->name) } @{ $self->files }
) {
my $in = path($distfile->name)->parent;
my $filename = $built_in->child( $distfile->name );
$archive->add(
$basedir->child( $distfile->name )->stringify,
$filename->stringify,
{ perm => (stat $filename)[2] & ~022 },
);
}
return $archive;
}
sub _prep_build_root {
my ($self, $build_root) = @_;
$build_root = path($build_root || $self->dist_basename);
$build_root->mkpath unless -d $build_root;
my $dist_root = $self->root;
return $build_root if !-d $build_root;
my $ok = eval { $build_root->remove_tree({ safe => 0 }); 1 };
die "unable to delete '$build_root' in preparation of build: $@" unless $ok;
# the following is done only on windows, and only if the deletion failed,
# yet rmtree reported success, because currently rmdir is non-blocking as per:
# https://rt.perl.org/Ticket/Display.html?id=123958
if ( $^O eq 'MSWin32' and -d $build_root ) {
$self->log("spinning for at least one second to allow other processes to release locks on $build_root");
my $timeout = time + 2;
while(time != $timeout and -d $build_root) { }
die "unable to delete '$build_root' in preparation of build because some process has a lock on it"
if -d $build_root;
}
return $build_root;
}
=method release
$zilla->release;
This method releases the distribution, probably by uploading it to the CPAN.
The actual effects of this method (as with most of the methods) is determined
by the loaded plugins.
=cut
sub release {
my $self = shift;
Carp::croak("you can't release without any Releaser plugins")
unless my @releasers = @{ $self->plugins_with(-Releaser) };
$ENV{DZIL_RELEASING} = 1;
my $tgz = $self->build_archive;
# call all plugins implementing BeforeRelease role
$_->before_release($tgz) for @{ $self->plugins_with(-BeforeRelease) };
# do the actual release
$_->release($tgz) for @releasers;
# call all plugins implementing AfterRelease role
$_->after_release($tgz) for @{ $self->plugins_with(-AfterRelease) };
}
=method clean
This method removes temporary files and directories suspected to have been
produced by the Dist::Zilla build process. Specifically, it deletes the
F<.build> directory and any entity that starts with the dist name and a hyphen,
like matching the glob C<Your-Dist-*>.
=cut
sub clean {
my ($self, $dry_run) = @_;
require File::Path;
for my $x (grep { -e } '.build', glob($self->name . '-*')) {
if ($dry_run) {
$self->log("clean: would remove $x");
} else {
$self->log("clean: removing $x");
File::Path::rmtree($x);
}
};
}
=method ensure_built_in_tmpdir
$zilla->ensure_built_in_tmpdir;
This method will consistently build the distribution in a temporary
subdirectory. It will return the path for the temporary build location.
=cut
sub ensure_built_in_tmpdir {
my $self = shift;
require File::Temp;
my $build_root = path('.build');
$build_root->mkpath unless -d $build_root;
my $target = path( File::Temp::tempdir(DIR => $build_root) );
$self->log("building distribution under $target for installation");
my $os_has_symlinks = eval { symlink("",""); 1 };
my $previous;
my $latest;
if( $os_has_symlinks ) {
$previous = path( $build_root, 'previous' );
$latest = path( $build_root, 'latest' );
if( -l $previous ) {
$previous->remove
or $self->log("cannot remove old .build/previous link");
}
if( -l $latest ) {
rename $latest, $previous
or $self->log("cannot move .build/latest link to .build/previous");
}
symlink $target->basename, $latest
or $self->log('cannot create link .build/latest');
}
$self->ensure_built_in($target);
return ($target, $latest, $previous);
}
=method install
$zilla->install( \%arg );
This method installs the distribution locally. The distribution will be built
in a temporary subdirectory, then the process will change directory to that
subdir and an installer will be run.
Valid arguments are:
keep_build_dir - if true, don't rmtree the build dir, even if everything
seemed to work
install_command - the command to run in the subdir to install the dist
default (roughly): $^X -MCPAN -einstall .
this argument should be an arrayref
=cut
sub install {
my ($self, $arg) = @_;
$arg ||= {};
my ($target, $latest) = $self->ensure_built_in_tmpdir;
my $ok = eval {
## no critic Punctuation
my $wd = File::pushd::pushd($target);
my @cmd = $arg->{install_command}
? @{ $arg->{install_command} }
: (cpanm => ".");
$self->log_debug([ 'installing via %s', \@cmd ]);
system(@cmd) && $self->log_fatal([ "error running %s", \@cmd ]);
1;
};
unless ($ok) {
my $error = $@ || '(exception clobered)';
$self->log("install failed, left failed dist in place at $target");
die $error;
}
if ($arg->{keep_build_dir}) {
$self->log("all's well; left dist in place at $target");
} else {
$self->log("all's well; removing $target");
$target->remove_tree({ safe => 0 });
$latest->remove_tree({ safe => 0 }) if -d $latest; # error cannot unlink, is a directory
$latest->remove if $latest;
}
return;
}
=method test
$zilla->test(\%arg);
This method builds a new copy of the distribution and tests it using
C<L</run_tests_in>>.
C<\%arg> may be omitted. Otherwise, valid arguments are:
keep_build_dir - if true, don't rmtree the build dir, even if everything
seemed to work
=cut
sub test {
my ($self, $arg) = @_;
Carp::croak("you can't test without any TestRunner plugins")
unless my @testers = @{ $self->plugins_with(-TestRunner) };
my ($target, $latest) = $self->ensure_built_in_tmpdir;
my $error = $self->run_tests_in($target, $arg);
if ($arg and $arg->{keep_build_dir}) {
$self->log("all's well; left dist in place at $target");
return;
}
$self->log("all's well; removing $target");
$target->remove_tree({ safe => 0 });
$latest->remove_tree({ safe => 0 }) if $latest && -d $latest; # error cannot unlink, is a directory
$latest->remove if $latest;
}
=method run_tests_in
my $error = $zilla->run_tests_in($directory, $arg);
This method runs the tests in $directory (a Path::Tiny), which must contain an
already-built copy of the distribution. It will throw an exception if there
are test failures.
It does I<not> set any of the C<*_TESTING> environment variables, nor
does it clean up C<$directory> afterwards.
=cut
sub run_tests_in {
my ($self, $target, $arg) = @_;
Carp::croak("you can't test without any TestRunner plugins")
unless my @testers = @{ $self->plugins_with(-TestRunner) };
for my $tester (@testers) {
my $wd = File::pushd::pushd($target);
$tester->test( $target, $arg );
}
}
=method run_in_build
$zilla->run_in_build( \@cmd );
This method makes a temporary directory, builds the distribution there,
executes all the dist's L<BuildRunner|Dist::Zilla::Role::BuildRunner>s
(unless directed not to, via C<< $arg->{build} = 0 >>), and
then runs the given command in the build directory. If the command exits
non-zero, the directory will be left in place.
=cut
sub run_in_build {
my ($self, $cmd, $arg) = @_;
$self->log_fatal("you can't build without any BuildRunner plugins")
unless ($arg and exists $arg->{build} and ! $arg->{build})
or @{ $self->plugins_with(-BuildRunner) };
require "Config.pm"; # skip autoprereq
my ($target, $latest) = $self->ensure_built_in_tmpdir;
my $abstarget = $target->absolute;
# building the dist for real
my $ok = eval {
my $wd = File::pushd::pushd($target);
if ($arg and exists $arg->{build} and ! $arg->{build}) {
system(@$cmd) and die "error while running: @$cmd";
return 1;
}
$self->_ensure_blib;
local $ENV{PERL5LIB} = join $Config::Config{path_sep},
(map { $abstarget->child('blib', $_) } qw(arch lib)),
(defined $ENV{PERL5LIB} ? $ENV{PERL5LIB} : ());
local $ENV{PATH} = join $Config::Config{path_sep},
(map { $abstarget->child('blib', $_) } qw(bin script)),
(defined $ENV{PATH} ? $ENV{PATH} : ());
system(@$cmd) and die "error while running: @$cmd";
1;
};
if ($ok) {
$self->log("all's well; removing $target");
$target->remove_tree({ safe => 0 });
$latest->remove_tree({ safe => 0 }) if -d $latest; # error cannot unlink, is a directory
$latest->remove if $latest;
} else {
my $error = $@ || '(unknown error)';
$self->log($error);
$self->log_fatal("left failed dist in place at $target");
}
}
# Ensures that a F<blib> directory exists in the build, by invoking all
# C<-BuildRunner> plugins to generate it. Useful for commands that operate on
# F<blib>, such as C<test> or C<run>.
sub _ensure_blib {
my ($self) = @_;
unless ( -d 'blib' ) {
my @builders = @{ $self->plugins_with( -BuildRunner ) };
$self->log_fatal("no BuildRunner plugins specified") unless @builders;
$_->build for @builders;
$self->log_fatal("no blib; failed to build properly?") unless -d 'blib';
}
}
__PACKAGE__->meta->make_immutable;
1;
|
rjbs/Dist-Zilla
|
dad3f65f84d746b20094ed3374e36b06a3ee6c19
|
.github/workflows/dzil-matrix.yaml: create
|
diff --git a/.github/workflows/dzil-matrix.yaml b/.github/workflows/dzil-matrix.yaml
new file mode 100644
index 0000000..cf4be1e
--- /dev/null
+++ b/.github/workflows/dzil-matrix.yaml
@@ -0,0 +1,12 @@
+name: "dzil matrix"
+on:
+ workflow_dispatch: ~
+ push:
+ branches: "*"
+ tags-ignore: "*"
+ pull_request: ~
+
+jobs:
+ build-and-test:
+ name: dzil-matrix
+ uses: rjbs/dzil-actions/.github/workflows/dzil-matrix.yaml@v0
|
rjbs/Dist-Zilla
|
dcb0b2a1550433eac78f55cd6af970d27959d8fb
|
GitHub Action: permit run on workflow_dispatch
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index 0fd7ece..e435d74 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,32 +1,33 @@
name: "multiperl test"
on:
+ workflow_dispatch: ~
push:
branches: "*"
tags-ignore: "*"
pull_request: ~
jobs:
build-tarball:
runs-on: ubuntu-latest
outputs:
perl-versions: ${{ steps.build-archive.outputs.perl-versions }}
steps:
- name: Build archive
id: build-archive
uses: rjbs/dzil-build@v0
multiperl-test:
needs: build-tarball
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version: ${{ fromJson(needs.build-tarball.outputs.perl-versions) }}
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Test distribution
uses: rjbs/test-perl-dist@v0
|
rjbs/Dist-Zilla
|
6e5ceba8ea35cdaa189f9df37e1a0702737c72fa
|
GitHub Action: rebuild for self-version-detecting workflow
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index 02ed9bd..0fd7ece 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,29 +1,32 @@
name: "multiperl test"
on:
push:
branches: "*"
tags-ignore: "*"
pull_request: ~
jobs:
build-tarball:
runs-on: ubuntu-latest
+ outputs:
+ perl-versions: ${{ steps.build-archive.outputs.perl-versions }}
steps:
- name: Build archive
+ id: build-archive
uses: rjbs/dzil-build@v0
multiperl-test:
needs: build-tarball
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
- perl-version: [ "devel", "5.38", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
+ perl-version: ${{ fromJson(needs.build-tarball.outputs.perl-versions) }}
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Test distribution
uses: rjbs/test-perl-dist@v0
|
rjbs/Dist-Zilla
|
589fd8d7f891ce9f2756a1dea21bf92c7851e231
|
GitHub Actions: workflow rebuild
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index 5953fab..02ed9bd 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,29 +1,29 @@
name: "multiperl test"
on:
push:
branches: "*"
tags-ignore: "*"
pull_request: ~
jobs:
build-tarball:
runs-on: ubuntu-latest
steps:
- - name: Build archive
- uses: rjbs/dzil-build@v0
+ - name: Build archive
+ uses: rjbs/dzil-build@v0
multiperl-test:
needs: build-tarball
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version: [ "devel", "5.38", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- - name: Test distribution
- uses: rjbs/test-perl-dist@v0
+ - name: Test distribution
+ uses: rjbs/test-perl-dist@v0
|
rjbs/Dist-Zilla
|
7f4a0914470d9071d4b2cb2c56d4008722a5ba3a
|
GitHub Actions: switch from @0 to @v0
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index 5c0af4a..5953fab 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,29 +1,29 @@
name: "multiperl test"
on:
push:
branches: "*"
tags-ignore: "*"
pull_request: ~
jobs:
build-tarball:
runs-on: ubuntu-latest
steps:
- name: Build archive
- uses: rjbs/dzil-build@0
+ uses: rjbs/dzil-build@v0
multiperl-test:
needs: build-tarball
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version: [ "devel", "5.38", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Test distribution
- uses: rjbs/test-perl-dist@0
+ uses: rjbs/test-perl-dist@v0
|
rjbs/Dist-Zilla
|
5ad75da55f446ab880eae745a076ef15b61e4535
|
GitHub Actions: switch from @main to @0 for rjbs actions
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index e3c595e..5c0af4a 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,29 +1,29 @@
name: "multiperl test"
on:
push:
branches: "*"
tags-ignore: "*"
pull_request: ~
jobs:
build-tarball:
runs-on: ubuntu-latest
steps:
- name: Build archive
- uses: rjbs/dzil-build@main
+ uses: rjbs/dzil-build@0
multiperl-test:
needs: build-tarball
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version: [ "devel", "5.38", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Test distribution
- uses: rjbs/test-perl-dist@main
+ uses: rjbs/test-perl-dist@0
|
rjbs/Dist-Zilla
|
88f50ffd9c8c6bd5da53e72d34f19e1c75999cff
|
use test-perl-dist action
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index 87b3255..e3c595e 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,64 +1,29 @@
name: "multiperl test"
on:
push:
branches: "*"
tags-ignore: "*"
pull_request: ~
-# FUTURE ENHANCEMENT(s):
-# * install faster (see below)
-# * use github.event.repository.name or ${GITHUB_REPOSITORY#*/} as the
-# tarball/build name instead of Dist-To-Test
-
jobs:
build-tarball:
runs-on: ubuntu-latest
- strategy:
- fail-fast: false
steps:
- name: Build archive
- uses: rjbs/dzil-test@main
+ uses: rjbs/dzil-build@main
multiperl-test:
needs: build-tarball
- env:
- # some plugins still needs this to run their tests...
- PERL_USE_UNSAFE_INC: 0
- AUTHOR_TESTING: 1
- AUTOMATED_TESTING: 1
-
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version: [ "devel", "5.38", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- - name: Download tarball
- uses: actions/download-artifact@v4
- with:
- name: Dist-To-Test.tar.gz
- - name: Extract tarball
- run: tar zxvf Dist-To-Test.tar.gz
- - name: Install dependencies
- working-directory: ./Dist-To-Test
- run: cpm install -g
- - name: Makefile.PL
- working-directory: ./Dist-To-Test
- run: perl Makefile.PL
- - name: Install yath
- run: cpm install -g Test2::Harness Test2::Harness::Renderer::JUnit
- - name: Run the tests
- working-directory: ./Dist-To-Test
- run: |
- JUNIT_TEST_FILE="/tmp/test-output.xml" ALLOW_PASSING_TODOS=1 yath test --renderer=Formatter --renderer=JUnit -D
- - name: Publish test report
- uses: mikepenz/action-junit-report@v4
- if: always() # always run even if the previous step fails
- with:
- check_name: JUnit Report (${{ matrix.perl-version }})
- report_paths: /tmp/test-output.xml
+ - name: Test distribution
+ uses: rjbs/test-perl-dist@main
|
rjbs/Dist-Zilla
|
2f65d2fd0542e10e7069dab5316cc9664dedcd6f
|
start using my own dzil test action
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index 91be012..87b3255 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,93 +1,64 @@
name: "multiperl test"
on:
push:
branches: "*"
tags-ignore: "*"
pull_request: ~
# FUTURE ENHANCEMENT(s):
# * install faster (see below)
# * use github.event.repository.name or ${GITHUB_REPOSITORY#*/} as the
# tarball/build name instead of Dist-To-Test
jobs:
build-tarball:
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- - name: Check out repo
- uses: actions/checkout@v4
- - name: Install cpm
- run: |
- curl https://raw.githubusercontent.com/skaji/cpm/main/cpm > /tmp/cpm
- chmod u+x /tmp/cpm
- - name: Install Dist::Zilla
- run: sudo apt-get install -y libdist-zilla-perl libdist-zilla-plugin-git-perl libpod-weaver-perl
- - name: Install authordeps
- run: |
- dzil authordeps --missing > /tmp/deps-phase-1.txt
- echo "---BEGIN AUTHORDEPS---"
- cat /tmp/deps-phase-1.txt
- echo "---END AUTHORDEPS---"
- sudo /tmp/cpm install -g - < /tmp/deps-phase-1.txt
- - name: Install missing prereqs
- run: |
- dzil listdeps --author --missing > /tmp/deps-phase-2.txt
- echo "---BEGIN PREREQS---"
- cat /tmp/deps-phase-2.txt
- echo "---END PREREQS---"
- sudo /tmp/cpm install -g - < /tmp/deps-phase-2.txt
- - name: Build tarball
- run: |
- dzil build --in Dist-To-Test
- tar zcvf Dist-To-Test.tar.gz Dist-To-Test
- - name: Upload tarball
- uses: actions/upload-artifact@v4
- with:
- name: Dist-To-Test.tar.gz
- path: Dist-To-Test.tar.gz
+ - name: Build archive
+ uses: rjbs/dzil-test@main
multiperl-test:
needs: build-tarball
env:
# some plugins still needs this to run their tests...
PERL_USE_UNSAFE_INC: 0
AUTHOR_TESTING: 1
AUTOMATED_TESTING: 1
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version: [ "devel", "5.38", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Download tarball
uses: actions/download-artifact@v4
with:
name: Dist-To-Test.tar.gz
- name: Extract tarball
run: tar zxvf Dist-To-Test.tar.gz
- name: Install dependencies
working-directory: ./Dist-To-Test
run: cpm install -g
- name: Makefile.PL
working-directory: ./Dist-To-Test
run: perl Makefile.PL
- name: Install yath
run: cpm install -g Test2::Harness Test2::Harness::Renderer::JUnit
- name: Run the tests
working-directory: ./Dist-To-Test
run: |
JUNIT_TEST_FILE="/tmp/test-output.xml" ALLOW_PASSING_TODOS=1 yath test --renderer=Formatter --renderer=JUnit -D
- name: Publish test report
uses: mikepenz/action-junit-report@v4
if: always() # always run even if the previous step fails
with:
check_name: JUnit Report (${{ matrix.perl-version }})
report_paths: /tmp/test-output.xml
|
rjbs/Dist-Zilla
|
f152fe41d2730e11acc9dc3734bd6cb35326995d
|
GitHub Action: rebuild from new workflower
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index 3049b70..91be012 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,95 +1,93 @@
name: "multiperl test"
on:
push:
branches: "*"
tags-ignore: "*"
pull_request: ~
# FUTURE ENHANCEMENT(s):
# * install faster (see below)
# * use github.event.repository.name or ${GITHUB_REPOSITORY#*/} as the
# tarball/build name instead of Dist-To-Test
jobs:
build-tarball:
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- name: Check out repo
uses: actions/checkout@v4
- name: Install cpm
run: |
curl https://raw.githubusercontent.com/skaji/cpm/main/cpm > /tmp/cpm
chmod u+x /tmp/cpm
- name: Install Dist::Zilla
run: sudo apt-get install -y libdist-zilla-perl libdist-zilla-plugin-git-perl libpod-weaver-perl
- name: Install authordeps
run: |
dzil authordeps --missing > /tmp/deps-phase-1.txt
echo "---BEGIN AUTHORDEPS---"
cat /tmp/deps-phase-1.txt
echo "---END AUTHORDEPS---"
sudo /tmp/cpm install -g - < /tmp/deps-phase-1.txt
- name: Install missing prereqs
run: |
dzil listdeps --author --missing > /tmp/deps-phase-2.txt
echo "---BEGIN PREREQS---"
cat /tmp/deps-phase-2.txt
echo "---END PREREQS---"
sudo /tmp/cpm install -g - < /tmp/deps-phase-2.txt
- name: Build tarball
run: |
dzil build --in Dist-To-Test
tar zcvf Dist-To-Test.tar.gz Dist-To-Test
- name: Upload tarball
uses: actions/upload-artifact@v4
with:
name: Dist-To-Test.tar.gz
path: Dist-To-Test.tar.gz
multiperl-test:
needs: build-tarball
env:
# some plugins still needs this to run their tests...
PERL_USE_UNSAFE_INC: 0
AUTHOR_TESTING: 1
AUTOMATED_TESTING: 1
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version: [ "devel", "5.38", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Download tarball
uses: actions/download-artifact@v4
with:
name: Dist-To-Test.tar.gz
- name: Extract tarball
run: tar zxvf Dist-To-Test.tar.gz
- name: Install dependencies
working-directory: ./Dist-To-Test
- run: cpanm --installdeps --notest .
+ run: cpm install -g
- name: Makefile.PL
working-directory: ./Dist-To-Test
run: perl Makefile.PL
- name: Install yath
- run: cpanm --notest Test2::Harness
- - name: Install testing libraries
- run: cpanm --notest Test2::Harness::Renderer::JUnit
+ run: cpm install -g Test2::Harness Test2::Harness::Renderer::JUnit
- name: Run the tests
working-directory: ./Dist-To-Test
run: |
JUNIT_TEST_FILE="/tmp/test-output.xml" ALLOW_PASSING_TODOS=1 yath test --renderer=Formatter --renderer=JUnit -D
- name: Publish test report
uses: mikepenz/action-junit-report@v4
if: always() # always run even if the previous step fails
with:
check_name: JUnit Report (${{ matrix.perl-version }})
report_paths: /tmp/test-output.xml
|
rjbs/Dist-Zilla
|
030f2f3b705cf4edc6e3eef8a2546aa078d26ab6
|
cpm workflow
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index 5748f42..3049b70 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,105 +1,95 @@
name: "multiperl test"
on:
push:
branches: "*"
tags-ignore: "*"
pull_request: ~
# FUTURE ENHANCEMENT(s):
# * install faster (see below)
# * use github.event.repository.name or ${GITHUB_REPOSITORY#*/} as the
# tarball/build name instead of Dist-To-Test
jobs:
build-tarball:
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- name: Check out repo
uses: actions/checkout@v4
- - name: Install cpanminus
+ - name: Install cpm
run: |
- curl https://cpanmin.us/ > /tmp/cpanm
- chmod u+x /tmp/cpanm
+ curl https://raw.githubusercontent.com/skaji/cpm/main/cpm > /tmp/cpm
+ chmod u+x /tmp/cpm
- name: Install Dist::Zilla
- run: sudo apt-get install -y libdist-zilla-perl
+ run: sudo apt-get install -y libdist-zilla-perl libdist-zilla-plugin-git-perl libpod-weaver-perl
- name: Install authordeps
run: |
dzil authordeps --missing > /tmp/deps-phase-1.txt
echo "---BEGIN AUTHORDEPS---"
cat /tmp/deps-phase-1.txt
echo "---END AUTHORDEPS---"
- /tmp/cpanm --notest -S < /tmp/deps-phase-1.txt
- - name: Upload cpanm logs for authordeps
- uses: actions/upload-artifact@v4
- with:
- name: cpanm-authordeps.log
- path: ~/.cpanm/build.log
+ sudo /tmp/cpm install -g - < /tmp/deps-phase-1.txt
- name: Install missing prereqs
run: |
dzil listdeps --author --missing > /tmp/deps-phase-2.txt
echo "---BEGIN PREREQS---"
cat /tmp/deps-phase-2.txt
echo "---END PREREQS---"
- /tmp/cpanm --notest -S < /tmp/deps-phase-2.txt
- - name: Upload cpanm logs for prereqs
- uses: actions/upload-artifact@v4
- with:
- name: cpanm-prereqs.log
- path: ~/.cpanm/build.log
+ sudo /tmp/cpm install -g - < /tmp/deps-phase-2.txt
- name: Build tarball
run: |
dzil build --in Dist-To-Test
tar zcvf Dist-To-Test.tar.gz Dist-To-Test
- name: Upload tarball
uses: actions/upload-artifact@v4
with:
name: Dist-To-Test.tar.gz
path: Dist-To-Test.tar.gz
multiperl-test:
needs: build-tarball
env:
# some plugins still needs this to run their tests...
PERL_USE_UNSAFE_INC: 0
AUTHOR_TESTING: 1
AUTOMATED_TESTING: 1
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version: [ "devel", "5.38", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Download tarball
uses: actions/download-artifact@v4
with:
name: Dist-To-Test.tar.gz
- name: Extract tarball
run: tar zxvf Dist-To-Test.tar.gz
- name: Install dependencies
working-directory: ./Dist-To-Test
run: cpanm --installdeps --notest .
- name: Makefile.PL
working-directory: ./Dist-To-Test
run: perl Makefile.PL
- name: Install yath
run: cpanm --notest Test2::Harness
- name: Install testing libraries
run: cpanm --notest Test2::Harness::Renderer::JUnit
- name: Run the tests
working-directory: ./Dist-To-Test
run: |
JUNIT_TEST_FILE="/tmp/test-output.xml" ALLOW_PASSING_TODOS=1 yath test --renderer=Formatter --renderer=JUnit -D
- name: Publish test report
uses: mikepenz/action-junit-report@v4
if: always() # always run even if the previous step fails
with:
check_name: JUnit Report (${{ matrix.perl-version }})
report_paths: /tmp/test-output.xml
|
rjbs/Dist-Zilla
|
f825e3b985867f58dd457dee378c7c3c335eee98
|
GitHub Actions: regenerate workflow
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index 1a51d4e..5748f42 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,90 +1,105 @@
name: "multiperl test"
on:
push:
branches: "*"
tags-ignore: "*"
pull_request: ~
# FUTURE ENHANCEMENT(s):
# * install faster (see below)
# * use github.event.repository.name or ${GITHUB_REPOSITORY#*/} as the
# tarball/build name instead of Dist-To-Test
jobs:
build-tarball:
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- name: Check out repo
uses: actions/checkout@v4
- name: Install cpanminus
run: |
curl https://cpanmin.us/ > /tmp/cpanm
chmod u+x /tmp/cpanm
- name: Install Dist::Zilla
run: sudo apt-get install -y libdist-zilla-perl
- - name: Install prereqs
- # This could probably be made more efficient by looking at what it's
- # installing via cpanm that could, instead, be installed from apt. I
- # may do that later, but for now, it's fine! -- rjbs, 2023-01-07
+ - name: Install authordeps
run: |
dzil authordeps --missing > /tmp/deps-phase-1.txt
+ echo "---BEGIN AUTHORDEPS---"
+ cat /tmp/deps-phase-1.txt
+ echo "---END AUTHORDEPS---"
/tmp/cpanm --notest -S < /tmp/deps-phase-1.txt
- dzil listdeps --author --missing >> /tmp/deps-phase-2.txt
+ - name: Upload cpanm logs for authordeps
+ uses: actions/upload-artifact@v4
+ with:
+ name: cpanm-authordeps.log
+ path: ~/.cpanm/build.log
+ - name: Install missing prereqs
+ run: |
+ dzil listdeps --author --missing > /tmp/deps-phase-2.txt
+ echo "---BEGIN PREREQS---"
+ cat /tmp/deps-phase-2.txt
+ echo "---END PREREQS---"
/tmp/cpanm --notest -S < /tmp/deps-phase-2.txt
+ - name: Upload cpanm logs for prereqs
+ uses: actions/upload-artifact@v4
+ with:
+ name: cpanm-prereqs.log
+ path: ~/.cpanm/build.log
- name: Build tarball
run: |
dzil build --in Dist-To-Test
tar zcvf Dist-To-Test.tar.gz Dist-To-Test
- name: Upload tarball
uses: actions/upload-artifact@v4
with:
name: Dist-To-Test.tar.gz
path: Dist-To-Test.tar.gz
multiperl-test:
needs: build-tarball
env:
# some plugins still needs this to run their tests...
PERL_USE_UNSAFE_INC: 0
AUTHOR_TESTING: 1
AUTOMATED_TESTING: 1
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version: [ "devel", "5.38", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Download tarball
uses: actions/download-artifact@v4
with:
name: Dist-To-Test.tar.gz
- name: Extract tarball
run: tar zxvf Dist-To-Test.tar.gz
- name: Install dependencies
working-directory: ./Dist-To-Test
run: cpanm --installdeps --notest .
- name: Makefile.PL
working-directory: ./Dist-To-Test
run: perl Makefile.PL
- name: Install yath
run: cpanm --notest Test2::Harness
- name: Install testing libraries
run: cpanm --notest Test2::Harness::Renderer::JUnit
- name: Run the tests
working-directory: ./Dist-To-Test
run: |
JUNIT_TEST_FILE="/tmp/test-output.xml" ALLOW_PASSING_TODOS=1 yath test --renderer=Formatter --renderer=JUnit -D
- name: Publish test report
uses: mikepenz/action-junit-report@v4
if: always() # always run even if the previous step fails
with:
check_name: JUnit Report (${{ matrix.perl-version }})
report_paths: /tmp/test-output.xml
|
rjbs/Dist-Zilla
|
aad24608f0dee98dc91cb0d42ee14be17d21a221
|
authordeps: expand some code to be easier to read
|
diff --git a/lib/Dist/Zilla/Util/AuthorDeps.pm b/lib/Dist/Zilla/Util/AuthorDeps.pm
index e960301..468a81c 100644
--- a/lib/Dist/Zilla/Util/AuthorDeps.pm
+++ b/lib/Dist/Zilla/Util/AuthorDeps.pm
@@ -1,135 +1,149 @@
package Dist::Zilla::Util::AuthorDeps;
# ABSTRACT: Utils for listing your distribution's author dependencies
use Dist::Zilla::Pragmas;
use Dist::Zilla::Util;
use Path::Tiny;
use List::Util 1.45 ();
use namespace::autoclean;
sub format_author_deps {
my ($reqs, $versions) = @_;
my $formatted = '';
foreach my $rec (@{ $reqs }) {
my ($mod, $ver) = each(%{ $rec });
$formatted .= $versions ? "$mod = $ver\n" : "$mod\n";
}
chomp($formatted);
return $formatted;
}
sub extract_author_deps {
my ($root, $missing) = @_;
my $ini = path($root, 'dist.ini');
die "dzil authordeps only works on dist.ini files, and you don't have one\n"
unless -e $ini;
my $fh = $ini->openr_utf8;
require Config::INI::Reader;
my $config = Config::INI::Reader->read_handle($fh);
require CPAN::Meta::Requirements;
my $reqs = CPAN::Meta::Requirements->new;
if (defined (my $license = $config->{_}->{license})) {
$license = 'Software::License::'.$license;
$reqs->add_minimum($license => 0);
}
for my $section ( sort keys %$config ) {
if (q[_] eq $section) {
my $version = $config->{_}{':version'};
$reqs->add_minimum('Dist::Zilla' => $version) if $version;
next;
}
my $pack = $section;
$pack =~ s{\s*/.*$}{}; # trim optional space and slash-delimited suffix
my $version = 0;
$version = $config->{$section}->{':version'} if exists $config->{$section}->{':version'};
my $realname = Dist::Zilla::Util->expand_config_package_name($pack);
$reqs->add_minimum($realname => $version);
}
seek $fh, 0, 0;
my $in_filter = 0;
while (<$fh>) {
next unless $in_filter or /^\[\s*\@Filter/;
$in_filter = 0, next if /^\[/ and ! /^\[\s*\@Filter/;
$in_filter = 1;
next unless /\A-bundle\s*=\s*([^;\s]+)/;
my $pname = $1;
chomp($pname);
$reqs->add_minimum(Dist::Zilla::Util->expand_config_package_name($1) => 0)
}
seek $fh, 0, 0;
my @packages;
while (<$fh>) {
chomp;
next unless /\A\s*;\s*authordep\s*(\S+)\s*(?:=\s*([^;]+))?\s*/;
my $module = $1;
my $ver = $2 // "0";
$ver =~ s/\s+$//;
# Any "; authordep " is inserted at the beginning of the list
# in the file order so the user can control the order of at least a part of
# the plugin list
push @packages, $module;
# And added to the requirements so we can use it later
$reqs->add_string_requirement($module => $ver);
}
my $vermap = $reqs->as_string_hash;
# Add the other requirements
push(@packages, sort keys %{ $vermap });
# Move inc:: first in list as they may impact the loading of other
# plugins (in particular local ones).
# Also order inc:: so that those that want to hack @INC with inc:: plugins
# can have a consistent playground.
# We don't sort the others packages to preserve the same (random) ordering
# for the common case (no inc::, no '; authordep') as in previous dzil
# releases.
@packages = ((sort grep /^inc::/, @packages), (grep !/^inc::/, @packages));
@packages = List::Util::uniq(@packages);
if ($missing) {
require Module::Runtime;
- @packages =
- grep {
- $_ eq 'perl'
- ? ! ($vermap->{perl} && eval "use $vermap->{perl}; 1")
- : do {
- my $m = $_;
- ! eval {
- local @INC = @INC; push @INC, "$root";
- # This will die if module is missing
- Module::Runtime::require_module($m);
- my $v = $vermap->{$m};
- # This will die if VERSION is too low
- !$v || $m->VERSION($v);
- # Success!
- 1
- }
- }
- } @packages;
+ my @new_packages;
+ PACKAGE: for my $package (@packages) {
+ if ($package eq 'perl') {
+ # This is weird, perl can never really be a prereq to fulfill but...
+ # it was like this. -- rjbs, 2024-06-02
+ if ($vermap->{perl} && ! eval "use $vermap->{perl}; 1") {
+ push @new_packages, 'perl';
+ }
+
+ next PACKAGE;
+ }
+
+ my $ok = eval {
+ local @INC = (@INC, "$root");
+
+ # This will die if module is missing
+ Module::Runtime::require_module($package);
+ my $v = $vermap->{$package};
+
+ # This will die if VERSION is too low
+ !$v || $package->VERSION($v);
+
+ # Success!
+ 1;
+ };
+
+ unless ($ok) {
+ push @new_packages, $package;
+ }
+ }
+
+ @packages = @new_packages;
}
# Now that we have a sorted list of packages, use that to build an array of
# hashrefs for display.
[ map { { $_ => $vermap->{$_} } } @packages ]
}
1;
|
rjbs/Dist-Zilla
|
3776ae04a52ac77083c82d4b20a599ba89c58d3b
|
GitHub Action: use v4 of junit report
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index eb939ef..1a51d4e 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,90 +1,90 @@
name: "multiperl test"
on:
push:
branches: "*"
tags-ignore: "*"
pull_request: ~
# FUTURE ENHANCEMENT(s):
# * install faster (see below)
# * use github.event.repository.name or ${GITHUB_REPOSITORY#*/} as the
# tarball/build name instead of Dist-To-Test
jobs:
build-tarball:
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- name: Check out repo
uses: actions/checkout@v4
- name: Install cpanminus
run: |
curl https://cpanmin.us/ > /tmp/cpanm
chmod u+x /tmp/cpanm
- name: Install Dist::Zilla
run: sudo apt-get install -y libdist-zilla-perl
- name: Install prereqs
# This could probably be made more efficient by looking at what it's
# installing via cpanm that could, instead, be installed from apt. I
# may do that later, but for now, it's fine! -- rjbs, 2023-01-07
run: |
dzil authordeps --missing > /tmp/deps-phase-1.txt
/tmp/cpanm --notest -S < /tmp/deps-phase-1.txt
dzil listdeps --author --missing >> /tmp/deps-phase-2.txt
/tmp/cpanm --notest -S < /tmp/deps-phase-2.txt
- name: Build tarball
run: |
dzil build --in Dist-To-Test
tar zcvf Dist-To-Test.tar.gz Dist-To-Test
- name: Upload tarball
uses: actions/upload-artifact@v4
with:
name: Dist-To-Test.tar.gz
path: Dist-To-Test.tar.gz
multiperl-test:
needs: build-tarball
env:
# some plugins still needs this to run their tests...
PERL_USE_UNSAFE_INC: 0
AUTHOR_TESTING: 1
AUTOMATED_TESTING: 1
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version: [ "devel", "5.38", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Download tarball
uses: actions/download-artifact@v4
with:
name: Dist-To-Test.tar.gz
- name: Extract tarball
run: tar zxvf Dist-To-Test.tar.gz
- name: Install dependencies
working-directory: ./Dist-To-Test
run: cpanm --installdeps --notest .
- name: Makefile.PL
working-directory: ./Dist-To-Test
run: perl Makefile.PL
- name: Install yath
run: cpanm --notest Test2::Harness
- name: Install testing libraries
run: cpanm --notest Test2::Harness::Renderer::JUnit
- name: Run the tests
working-directory: ./Dist-To-Test
run: |
JUNIT_TEST_FILE="/tmp/test-output.xml" ALLOW_PASSING_TODOS=1 yath test --renderer=Formatter --renderer=JUnit -D
- name: Publish test report
- uses: mikepenz/action-junit-report@v3
+ uses: mikepenz/action-junit-report@v4
if: always() # always run even if the previous step fails
with:
check_name: JUnit Report (${{ matrix.perl-version }})
report_paths: /tmp/test-output.xml
|
rjbs/Dist-Zilla
|
69151353c9efd2160034cbbd1044d4c84ba6eeea
|
GitHub Action: also build on v5.38
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index 3d76b2f..eb939ef 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,90 +1,90 @@
name: "multiperl test"
on:
push:
branches: "*"
tags-ignore: "*"
pull_request: ~
# FUTURE ENHANCEMENT(s):
# * install faster (see below)
# * use github.event.repository.name or ${GITHUB_REPOSITORY#*/} as the
# tarball/build name instead of Dist-To-Test
jobs:
build-tarball:
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- name: Check out repo
uses: actions/checkout@v4
- name: Install cpanminus
run: |
curl https://cpanmin.us/ > /tmp/cpanm
chmod u+x /tmp/cpanm
- name: Install Dist::Zilla
run: sudo apt-get install -y libdist-zilla-perl
- name: Install prereqs
# This could probably be made more efficient by looking at what it's
# installing via cpanm that could, instead, be installed from apt. I
# may do that later, but for now, it's fine! -- rjbs, 2023-01-07
run: |
dzil authordeps --missing > /tmp/deps-phase-1.txt
- /tmp/cpanm --notest -S < /tmp/deps-phase-1.txt || cat ~/.cpanm/build.log
+ /tmp/cpanm --notest -S < /tmp/deps-phase-1.txt
dzil listdeps --author --missing >> /tmp/deps-phase-2.txt
- /tmp/cpanm --notest -S < /tmp/deps-phase-2.txt || cat ~/.cpanm/build.log
+ /tmp/cpanm --notest -S < /tmp/deps-phase-2.txt
- name: Build tarball
run: |
dzil build --in Dist-To-Test
tar zcvf Dist-To-Test.tar.gz Dist-To-Test
- name: Upload tarball
uses: actions/upload-artifact@v4
with:
name: Dist-To-Test.tar.gz
path: Dist-To-Test.tar.gz
multiperl-test:
needs: build-tarball
env:
# some plugins still needs this to run their tests...
PERL_USE_UNSAFE_INC: 0
AUTHOR_TESTING: 1
AUTOMATED_TESTING: 1
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
- perl-version: [ "devel", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
+ perl-version: [ "devel", "5.38", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Download tarball
uses: actions/download-artifact@v4
with:
name: Dist-To-Test.tar.gz
- name: Extract tarball
run: tar zxvf Dist-To-Test.tar.gz
- name: Install dependencies
working-directory: ./Dist-To-Test
run: cpanm --installdeps --notest .
- name: Makefile.PL
working-directory: ./Dist-To-Test
run: perl Makefile.PL
- name: Install yath
run: cpanm --notest Test2::Harness
- name: Install testing libraries
run: cpanm --notest Test2::Harness::Renderer::JUnit
- name: Run the tests
working-directory: ./Dist-To-Test
run: |
JUNIT_TEST_FILE="/tmp/test-output.xml" ALLOW_PASSING_TODOS=1 yath test --renderer=Formatter --renderer=JUnit -D
- name: Publish test report
uses: mikepenz/action-junit-report@v3
if: always() # always run even if the previous step fails
with:
check_name: JUnit Report (${{ matrix.perl-version }})
report_paths: /tmp/test-output.xml
|
rjbs/Dist-Zilla
|
5f7920b0f924a370920d6dfff4cfb2a362d338eb
|
GitHub Action: dump build.log on prereq install failure
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index 059ab4a..3d76b2f 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,90 +1,90 @@
name: "multiperl test"
on:
push:
branches: "*"
tags-ignore: "*"
pull_request: ~
# FUTURE ENHANCEMENT(s):
# * install faster (see below)
# * use github.event.repository.name or ${GITHUB_REPOSITORY#*/} as the
# tarball/build name instead of Dist-To-Test
jobs:
build-tarball:
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- name: Check out repo
uses: actions/checkout@v4
- name: Install cpanminus
run: |
curl https://cpanmin.us/ > /tmp/cpanm
chmod u+x /tmp/cpanm
- name: Install Dist::Zilla
run: sudo apt-get install -y libdist-zilla-perl
- name: Install prereqs
# This could probably be made more efficient by looking at what it's
# installing via cpanm that could, instead, be installed from apt. I
# may do that later, but for now, it's fine! -- rjbs, 2023-01-07
run: |
dzil authordeps --missing > /tmp/deps-phase-1.txt
- /tmp/cpanm --notest -S < /tmp/deps-phase-1.txt
+ /tmp/cpanm --notest -S < /tmp/deps-phase-1.txt || cat ~/.cpanm/build.log
dzil listdeps --author --missing >> /tmp/deps-phase-2.txt
- /tmp/cpanm --notest -S < /tmp/deps-phase-2.txt
+ /tmp/cpanm --notest -S < /tmp/deps-phase-2.txt || cat ~/.cpanm/build.log
- name: Build tarball
run: |
dzil build --in Dist-To-Test
tar zcvf Dist-To-Test.tar.gz Dist-To-Test
- name: Upload tarball
uses: actions/upload-artifact@v4
with:
name: Dist-To-Test.tar.gz
path: Dist-To-Test.tar.gz
multiperl-test:
needs: build-tarball
env:
# some plugins still needs this to run their tests...
PERL_USE_UNSAFE_INC: 0
AUTHOR_TESTING: 1
AUTOMATED_TESTING: 1
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version: [ "devel", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Download tarball
uses: actions/download-artifact@v4
with:
name: Dist-To-Test.tar.gz
- name: Extract tarball
run: tar zxvf Dist-To-Test.tar.gz
- name: Install dependencies
working-directory: ./Dist-To-Test
run: cpanm --installdeps --notest .
- name: Makefile.PL
working-directory: ./Dist-To-Test
run: perl Makefile.PL
- name: Install yath
run: cpanm --notest Test2::Harness
- name: Install testing libraries
run: cpanm --notest Test2::Harness::Renderer::JUnit
- name: Run the tests
working-directory: ./Dist-To-Test
run: |
JUNIT_TEST_FILE="/tmp/test-output.xml" ALLOW_PASSING_TODOS=1 yath test --renderer=Formatter --renderer=JUnit -D
- name: Publish test report
uses: mikepenz/action-junit-report@v3
if: always() # always run even if the previous step fails
with:
check_name: JUnit Report (${{ matrix.perl-version }})
report_paths: /tmp/test-output.xml
|
rjbs/Dist-Zilla
|
d57dd9d7f20c75ec98fab52203af21baf7a8ee7d
|
v6.032
|
diff --git a/Changes b/Changes
index 7128d8b..1504385 100644
--- a/Changes
+++ b/Changes
@@ -1,515 +1,517 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+
+6.032 2024-05-25 12:30:02-04:00 America/New_York
- UploadToCPAN errors will distinguish between "couldn't find password"
and "something went wrong trying to get password"
- UploadToCPAN can now use any Login-type stash for credentials, not
just a PAUSE-class stash
6.031 2023-11-20 19:49:23-05:00 America/New_York
- avoid some warnings on platforms without symlinks; (thanks, reneeb!)
6.030 2023-01-18 21:36:40-05:00 America/New_York
- "dzil new" will use command line options before configuration
- "dzil add" now falls back to %Mint stash options before defaults
(for both of the above: thanks, Graham Knop!)
6.029 2022-11-25 17:02:33-05:00 America/New_York
- update some links to use https instead of http (thanks, Elvin
Aslanov)
- turn on strict and warnings in generated author tests (thanks, Mark
Flickinger)
- use "v1.2.3" for multi-dot versions in "package NAME VERSION" formats
(thanks, Branislav ZahradnÃk)
- fixes to operation on msys (thanks, Paulo Custodio)
- add "main_module" option to MakeMaker (thanks, Tatsuhiko Miyagawa)
- fix authordeps behavior; don't add an object to @INC (thanks, Shoichi
Kaji)
6.028 2022-11-09 10:54:14-05:00 America/New_York
- remove bogus work-in-progress signatures-using commit from 6.027;
that was a bad release! thanks for the heads-up about it to Gianni
"dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
|
rjbs/Dist-Zilla
|
ca23519af15c857d7d56b80f033ebfc8ca9c65ee
|
Changes: update for UploadToCPAN changes
|
diff --git a/Changes b/Changes
index 6b12f7b..7128d8b 100644
--- a/Changes
+++ b/Changes
@@ -1,515 +1,519 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+ - UploadToCPAN errors will distinguish between "couldn't find password"
+ and "something went wrong trying to get password"
+ - UploadToCPAN can now use any Login-type stash for credentials, not
+ just a PAUSE-class stash
6.031 2023-11-20 19:49:23-05:00 America/New_York
- avoid some warnings on platforms without symlinks; (thanks, reneeb!)
6.030 2023-01-18 21:36:40-05:00 America/New_York
- "dzil new" will use command line options before configuration
- "dzil add" now falls back to %Mint stash options before defaults
(for both of the above: thanks, Graham Knop!)
6.029 2022-11-25 17:02:33-05:00 America/New_York
- update some links to use https instead of http (thanks, Elvin
Aslanov)
- turn on strict and warnings in generated author tests (thanks, Mark
Flickinger)
- use "v1.2.3" for multi-dot versions in "package NAME VERSION" formats
(thanks, Branislav ZahradnÃk)
- fixes to operation on msys (thanks, Paulo Custodio)
- add "main_module" option to MakeMaker (thanks, Tatsuhiko Miyagawa)
- fix authordeps behavior; don't add an object to @INC (thanks, Shoichi
Kaji)
6.028 2022-11-09 10:54:14-05:00 America/New_York
- remove bogus work-in-progress signatures-using commit from 6.027;
that was a bad release! thanks for the heads-up about it to Gianni
"dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
|
rjbs/Dist-Zilla
|
e673ae37fba19bd5071f72b17fe86b3f0b336b04
|
UploadToCPAN: change how we report on problems with credentials
|
diff --git a/lib/Dist/Zilla/Plugin/UploadToCPAN.pm b/lib/Dist/Zilla/Plugin/UploadToCPAN.pm
index a29f9ef..b349f6e 100644
--- a/lib/Dist/Zilla/Plugin/UploadToCPAN.pm
+++ b/lib/Dist/Zilla/Plugin/UploadToCPAN.pm
@@ -1,307 +1,313 @@
package Dist::Zilla::Plugin::UploadToCPAN;
# ABSTRACT: upload the dist to CPAN
use Moose;
with 'Dist::Zilla::Role::BeforeRelease',
'Dist::Zilla::Role::Releaser';
use Dist::Zilla::Pragmas;
use File::Spec;
use Moose::Util::TypeConstraints;
use Scalar::Util qw(weaken);
use Dist::Zilla::Util;
use Try::Tiny;
use namespace::autoclean;
=head1 SYNOPSIS
If loaded, this plugin will allow the F<release> command to upload to the CPAN.
=head1 DESCRIPTION
This plugin looks for configuration in your C<dist.ini> or (more
likely) C<~/.dzil/config.ini>:
[%PAUSE]
username = YOUR-PAUSE-ID
password = YOUR-PAUSE-PASSWORD
If this configuration does not exist, it can read the configuration from
C<~/.pause>, in the same format that L<cpan-upload> requires:
user YOUR-PAUSE-ID
password YOUR-PAUSE-PASSWORD
If neither configuration exists, it will prompt you to enter your
username and password during the BeforeRelease phase. Entering a
blank username or password will abort the release.
You can't put your password in your F<dist.ini>. C'mon now!
=cut
{
package
Dist::Zilla::Plugin::UploadToCPAN::_Uploader;
# CPAN::Uploader will be loaded later if used
our @ISA = 'CPAN::Uploader';
# Report CPAN::Uploader's version, not ours:
sub _ua_string { CPAN::Uploader->_ua_string }
sub log {
my $self = shift;
$self->{'Dist::Zilla'}{plugin}->log(@_);
}
}
=attr credentials_stash
This attribute holds the name of a L<PAUSE stash|Dist::Zilla::Stash::Login>
that will contain the credentials to be used for the upload. By default,
UploadToCPAN will look for a C<%PAUSE> stash.
=cut
has credentials_stash => (
is => 'ro',
isa => 'Str',
default => '%PAUSE'
);
has _credentials_stash_obj => (
is => 'ro',
isa => maybe_type( role_type('Dist::Zilla::Role::Stash::Login') ),
lazy => 1,
init_arg => undef,
default => sub { $_[0]->zilla->stash_named( $_[0]->credentials_stash ) },
);
sub _credential {
my ($self, $name) = @_;
return unless my $stash = $self->_credentials_stash_obj;
return $stash->$name;
}
sub mvp_aliases {
return { user => 'username' };
}
=attr username
This option supplies the user's PAUSE username.
It will be looked for in the user's PAUSE configuration; if not
found, the user will be prompted.
=cut
has username => (
is => 'ro',
isa => 'Str',
lazy => 1,
default => sub {
my ($self) = @_;
return $self->_credential('username')
|| $self->pause_cfg->{user}
|| $self->zilla->chrome->prompt_str("PAUSE username: ");
},
);
sub cpanid { shift->username }
=attr password
This option supplies the user's PAUSE password. It cannot be provided via
F<dist.ini>. It will be looked for in the user's PAUSE configuration; if not
found, the user will be prompted.
=cut
has password => (
is => 'ro',
isa => 'Str',
init_arg => undef,
lazy => 1,
default => sub {
my ($self) = @_;
my $pw = $self->_credential('password') || $self->pause_cfg->{password};
unless ($pw){
my $uname = $self->username;
$pw = $self->zilla->chrome->prompt_str(
"PAUSE password for $uname: ",
{ noecho => 1 },
);
}
return $pw;
},
);
=attr pause_cfg_file
This is the name of the file containing your pause credentials. It defaults
F<.pause>. If you give a relative path, it is taken to be relative to
L</pause_cfg_dir>.
=cut
has pause_cfg_file => (
is => 'ro',
isa => 'Str',
lazy => 1,
default => sub { '.pause' },
);
=attr pause_cfg_dir
This is the directory for resolving a relative L</pause_cfg_file>.
it defaults to the glob expansion of F<~>.
=cut
has pause_cfg_dir => (
is => 'ro',
isa => 'Str',
lazy => 1,
default => sub { Dist::Zilla::Util->homedir },
);
=attr pause_cfg
This is a hashref of defaults loaded from F<~/.pause> -- this attribute is
subject to removal in future versions, as the config-loading behavior in
CPAN::Uploader is improved.
=cut
has pause_cfg => (
is => 'ro',
isa => 'HashRef[Str]',
lazy => 1,
default => sub {
my $self = shift;
require CPAN::Uploader;
my $file = $self->pause_cfg_file;
$file = File::Spec->catfile($self->pause_cfg_dir, $file)
unless File::Spec->file_name_is_absolute($file);
return {} unless -e $file && -r _;
my $cfg = try {
CPAN::Uploader->read_config_file($file)
} catch {
$self->log("Couldn't load credentials from '$file': $_");
{};
};
return $cfg;
},
);
=attr subdir
If given, this specifies a subdirectory under the user's home directory to
which to upload. Using this option is not recommended.
=cut
has subdir => (
is => 'ro',
isa => 'Str',
predicate => 'has_subdir',
);
=attr upload_uri
If given, this specifies an alternate URI for the PAUSE upload form. By
default, the default supplied by L<CPAN::Uploader> is used. Using this option
is not recommended in most cases.
=cut
has upload_uri => (
is => 'ro',
isa => 'Str',
predicate => 'has_upload_uri',
);
=attr retries
The number of retries to perform on upload failure (5xx response). The default
is set to 3 by this plugin. This option will be passed to L<CPAN::Uploader>.
=cut
has retries => (
is => 'ro',
isa => 'Int',
default => 3,
);
=attr retry_delay
The number of seconds to wait between retries. The default is set to 5 seconds
by this plugin. This option will be passed to L<CPAN::Uploader>.
=cut
has retry_delay => (
is => 'ro',
isa => 'Int',
default => 5,
);
has uploader => (
is => 'ro',
isa => 'CPAN::Uploader',
lazy => 1,
default => sub {
my ($self) = @_;
# Load the module lazily
require CPAN::Uploader;
CPAN::Uploader->VERSION('0.103004'); # require HTTPS
my $uploader = Dist::Zilla::Plugin::UploadToCPAN::_Uploader->new({
user => $self->username,
password => $self->password,
($self->has_subdir
? (subdir => $self->subdir) : ()),
($self->has_upload_uri
? (upload_uri => $self->upload_uri) : ()),
($self->retries
? (retries => $self->retries) : ()),
($self->retry_delay
? (retry_delay => $self->retry_delay) : ()),
});
$uploader->{'Dist::Zilla'}{plugin} = $self;
weaken $uploader->{'Dist::Zilla'}{plugin};
return $uploader;
}
);
sub before_release {
my $self = shift;
- my $problem;
- try {
- for my $attr (qw(username password)) {
- $problem = $attr;
- die unless length $self->$attr;
+ my $sentinel = [];
+
+ for my $attr (qw(username password)) {
+ my $value;
+ my $ok = eval { $value = $self->$attr; 1 };
+
+ unless ($ok) {
+ $self->log_fatal([ "Couldn't figure out %s: %s", $attr, $@ ]);
}
- undef $problem;
- };
- $self->log_fatal(['You need to supply a %s', $problem]) if $problem;
+ unless (length $value) {
+ $self->log_fatal([ "No $attr was provided" ]);
+ }
+ }
+
+ return;
}
sub release {
my ($self, $archive) = @_;
$self->uploader->upload_file("$archive");
}
__PACKAGE__->meta->make_immutable;
1;
diff --git a/t/plugins/uploadtocpan.t b/t/plugins/uploadtocpan.t
index 94e581c..f08e57d 100644
--- a/t/plugins/uploadtocpan.t
+++ b/t/plugins/uploadtocpan.t
@@ -1,158 +1,158 @@
use strict;
use warnings;
use Test::More 0.88 tests => 17;
use File::Spec ();
use Test::DZil qw(Builder simple_ini);
use Test::Fatal qw(exception);
#---------------------------------------------------------------------
# Install a fake upload_file method for testing purposes:
sub Dist::Zilla::Plugin::UploadToCPAN::_Uploader::upload_file {
my ($self, $archive) = @_;
$self->log("PAUSE $_ is $self->{$_}") for qw(user password);
$self->log("Uploading $archive") if -f $archive;
}
#---------------------------------------------------------------------
# Create a Builder with a simple configuration:
sub build_tzil {
Builder->from_config(
{ dist_root => 'corpus/dist/DZT' },
{
add_files => {
'source/dist.ini' => simple_ini('GatherDir', @_),
},
},
);
}
#---------------------------------------------------------------------
# Set responses for the username and password prompts:
sub set_responses {
my ($zilla, $username, $pw) = @_;
$zilla->chrome->set_response_for('PAUSE username: ', $username);
$zilla->chrome->set_response_for("PAUSE password for $username: ", $pw);
}
#---------------------------------------------------------------------
# Pass invalid upload_uri to UploadToCPAN as an extra precaution,
# and don't let it look for ~/.pause:
my %safety_first = (qw(upload_uri http://bogus.example.com/do/not/upload/),
pause_cfg_file => File::Spec->devnull);
#---------------------------------------------------------------------
# config from %PAUSE stash in dist.ini:
{
my $tzil = build_tzil(
[ UploadToCPAN => { %safety_first } ],
'FakeRelease',
[ '%PAUSE' => {qw(
username user
password password
)}],
);
$tzil->release;
my $msgs = $tzil->log_messages;
ok(grep({ /PAUSE user is user/ } @$msgs), "read username");
ok(grep({ /PAUSE password is password/ } @$msgs), "read password");
ok(grep({ /Uploading.*DZT-Sample/ } @$msgs), "uploaded archive");
ok(
grep({ /fake release happen/i } @$msgs),
"releasing continues after upload",
);
}
#---------------------------------------------------------------------
# Config from user input:
{
my $tzil = build_tzil(
[ UploadToCPAN => { %safety_first } ],
'FakeRelease',
);
set_responses($tzil, qw(user password));
$tzil->release;
my $msgs = $tzil->log_messages;
ok(grep({ /PAUSE user is user/ } @$msgs), "entered username");
ok(grep({ /PAUSE password is password/ } @$msgs), "entered password");
ok(grep({ /Uploading.*DZT-Sample/ } @$msgs), "uploaded archive manually");
ok(
grep({ /fake release happen/i } @$msgs),
"releasing continues after manual upload",
);
}
#---------------------------------------------------------------------
# No config at all:
{
my $tzil = build_tzil(
'FakeRelease',
[ UploadToCPAN => { %safety_first } ],
);
# Pretend user just hits Enter at the prompts:
set_responses($tzil, '', '');
like( exception { $tzil->release },
- qr/You need to supply a username/,
+ qr/No username was provided/,
"release without credentials fails");
my $msgs = $tzil->log_messages;
- ok(grep({ /You need to supply a username/} @$msgs), "insist on username");
+ ok(grep({ /No username was provided/} @$msgs), "insist on username");
ok(!grep({ /Uploading.*DZT-Sample/ } @$msgs), "no upload without credentials");
ok(
!grep({ /fake release happen/i } @$msgs),
"no release without credentials"
);
}
#---------------------------------------------------------------------
# No config at all, but enter username:
{
my $tzil = build_tzil(
'FakeRelease',
[ UploadToCPAN => { %safety_first } ],
);
# Pretend user just hits Enter at the password prompt:
set_responses($tzil, 'user', '');
like( exception { $tzil->release },
- qr/You need to supply a password/,
+ qr/No password was provided/,
"release without password fails");
my $msgs = $tzil->log_messages;
- ok(grep({ /You need to supply a password/} @$msgs), "insist on password");
+ ok(grep({ /No password was provided/} @$msgs), "insist on password");
ok(!grep({ /Uploading.*DZT-Sample/ } @$msgs), "no upload without password");
ok(
!grep({ /fake release happen/i } @$msgs),
"no release without password"
);
}
# Config from dist.ini
{
my $tzil = build_tzil(
'FakeRelease',
[ UploadToCPAN => {
%safety_first,
username => 'me',
password => 'ohhai',
}
],
);
like( exception { $tzil->release },
- qr/You need to supply a password/,
+ qr/Couldn't figure out password/,
"password set in dist.ini is ignored");
}
|
rjbs/Dist-Zilla
|
4bdaadd3170711db6fb86746dada8ffed592f66b
|
UploadToCPAN: only require a Login stash, not a PAUSE
|
diff --git a/lib/Dist/Zilla/Plugin/UploadToCPAN.pm b/lib/Dist/Zilla/Plugin/UploadToCPAN.pm
index c1e3f67..a29f9ef 100644
--- a/lib/Dist/Zilla/Plugin/UploadToCPAN.pm
+++ b/lib/Dist/Zilla/Plugin/UploadToCPAN.pm
@@ -1,307 +1,307 @@
package Dist::Zilla::Plugin::UploadToCPAN;
# ABSTRACT: upload the dist to CPAN
use Moose;
with 'Dist::Zilla::Role::BeforeRelease',
'Dist::Zilla::Role::Releaser';
use Dist::Zilla::Pragmas;
use File::Spec;
use Moose::Util::TypeConstraints;
use Scalar::Util qw(weaken);
use Dist::Zilla::Util;
use Try::Tiny;
use namespace::autoclean;
=head1 SYNOPSIS
If loaded, this plugin will allow the F<release> command to upload to the CPAN.
=head1 DESCRIPTION
This plugin looks for configuration in your C<dist.ini> or (more
likely) C<~/.dzil/config.ini>:
[%PAUSE]
username = YOUR-PAUSE-ID
password = YOUR-PAUSE-PASSWORD
If this configuration does not exist, it can read the configuration from
C<~/.pause>, in the same format that L<cpan-upload> requires:
user YOUR-PAUSE-ID
password YOUR-PAUSE-PASSWORD
If neither configuration exists, it will prompt you to enter your
username and password during the BeforeRelease phase. Entering a
blank username or password will abort the release.
You can't put your password in your F<dist.ini>. C'mon now!
=cut
{
package
Dist::Zilla::Plugin::UploadToCPAN::_Uploader;
# CPAN::Uploader will be loaded later if used
our @ISA = 'CPAN::Uploader';
# Report CPAN::Uploader's version, not ours:
sub _ua_string { CPAN::Uploader->_ua_string }
sub log {
my $self = shift;
$self->{'Dist::Zilla'}{plugin}->log(@_);
}
}
=attr credentials_stash
-This attribute holds the name of a L<PAUSE stash|Dist::Zilla::Stash::PAUSE>
+This attribute holds the name of a L<PAUSE stash|Dist::Zilla::Stash::Login>
that will contain the credentials to be used for the upload. By default,
UploadToCPAN will look for a C<%PAUSE> stash.
=cut
has credentials_stash => (
is => 'ro',
isa => 'Str',
default => '%PAUSE'
);
has _credentials_stash_obj => (
is => 'ro',
- isa => maybe_type( class_type('Dist::Zilla::Stash::PAUSE') ),
+ isa => maybe_type( role_type('Dist::Zilla::Role::Stash::Login') ),
lazy => 1,
init_arg => undef,
default => sub { $_[0]->zilla->stash_named( $_[0]->credentials_stash ) },
);
sub _credential {
my ($self, $name) = @_;
return unless my $stash = $self->_credentials_stash_obj;
return $stash->$name;
}
sub mvp_aliases {
return { user => 'username' };
}
=attr username
This option supplies the user's PAUSE username.
It will be looked for in the user's PAUSE configuration; if not
found, the user will be prompted.
=cut
has username => (
is => 'ro',
isa => 'Str',
lazy => 1,
default => sub {
my ($self) = @_;
return $self->_credential('username')
|| $self->pause_cfg->{user}
|| $self->zilla->chrome->prompt_str("PAUSE username: ");
},
);
sub cpanid { shift->username }
=attr password
This option supplies the user's PAUSE password. It cannot be provided via
F<dist.ini>. It will be looked for in the user's PAUSE configuration; if not
found, the user will be prompted.
=cut
has password => (
is => 'ro',
isa => 'Str',
init_arg => undef,
lazy => 1,
default => sub {
my ($self) = @_;
my $pw = $self->_credential('password') || $self->pause_cfg->{password};
unless ($pw){
my $uname = $self->username;
$pw = $self->zilla->chrome->prompt_str(
"PAUSE password for $uname: ",
{ noecho => 1 },
);
}
return $pw;
},
);
=attr pause_cfg_file
This is the name of the file containing your pause credentials. It defaults
F<.pause>. If you give a relative path, it is taken to be relative to
L</pause_cfg_dir>.
=cut
has pause_cfg_file => (
is => 'ro',
isa => 'Str',
lazy => 1,
default => sub { '.pause' },
);
=attr pause_cfg_dir
This is the directory for resolving a relative L</pause_cfg_file>.
it defaults to the glob expansion of F<~>.
=cut
has pause_cfg_dir => (
is => 'ro',
isa => 'Str',
lazy => 1,
default => sub { Dist::Zilla::Util->homedir },
);
=attr pause_cfg
This is a hashref of defaults loaded from F<~/.pause> -- this attribute is
subject to removal in future versions, as the config-loading behavior in
CPAN::Uploader is improved.
=cut
has pause_cfg => (
is => 'ro',
isa => 'HashRef[Str]',
lazy => 1,
default => sub {
my $self = shift;
require CPAN::Uploader;
my $file = $self->pause_cfg_file;
$file = File::Spec->catfile($self->pause_cfg_dir, $file)
unless File::Spec->file_name_is_absolute($file);
return {} unless -e $file && -r _;
my $cfg = try {
CPAN::Uploader->read_config_file($file)
} catch {
$self->log("Couldn't load credentials from '$file': $_");
{};
};
return $cfg;
},
);
=attr subdir
If given, this specifies a subdirectory under the user's home directory to
which to upload. Using this option is not recommended.
=cut
has subdir => (
is => 'ro',
isa => 'Str',
predicate => 'has_subdir',
);
=attr upload_uri
If given, this specifies an alternate URI for the PAUSE upload form. By
default, the default supplied by L<CPAN::Uploader> is used. Using this option
is not recommended in most cases.
=cut
has upload_uri => (
is => 'ro',
isa => 'Str',
predicate => 'has_upload_uri',
);
=attr retries
The number of retries to perform on upload failure (5xx response). The default
is set to 3 by this plugin. This option will be passed to L<CPAN::Uploader>.
=cut
has retries => (
is => 'ro',
isa => 'Int',
default => 3,
);
=attr retry_delay
The number of seconds to wait between retries. The default is set to 5 seconds
by this plugin. This option will be passed to L<CPAN::Uploader>.
=cut
has retry_delay => (
is => 'ro',
isa => 'Int',
default => 5,
);
has uploader => (
is => 'ro',
isa => 'CPAN::Uploader',
lazy => 1,
default => sub {
my ($self) = @_;
# Load the module lazily
require CPAN::Uploader;
CPAN::Uploader->VERSION('0.103004'); # require HTTPS
my $uploader = Dist::Zilla::Plugin::UploadToCPAN::_Uploader->new({
user => $self->username,
password => $self->password,
($self->has_subdir
? (subdir => $self->subdir) : ()),
($self->has_upload_uri
? (upload_uri => $self->upload_uri) : ()),
($self->retries
? (retries => $self->retries) : ()),
($self->retry_delay
? (retry_delay => $self->retry_delay) : ()),
});
$uploader->{'Dist::Zilla'}{plugin} = $self;
weaken $uploader->{'Dist::Zilla'}{plugin};
return $uploader;
}
);
sub before_release {
my $self = shift;
my $problem;
try {
for my $attr (qw(username password)) {
$problem = $attr;
die unless length $self->$attr;
}
undef $problem;
};
$self->log_fatal(['You need to supply a %s', $problem]) if $problem;
}
sub release {
my ($self, $archive) = @_;
$self->uploader->upload_file("$archive");
}
__PACKAGE__->meta->make_immutable;
1;
|
rjbs/Dist-Zilla
|
b8b9b6559aad248e01e181b4903bdf6059308234
|
GitHub Action: rebuild workflower
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index d9e1345..059ab4a 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,90 +1,90 @@
name: "multiperl test"
on:
push:
branches: "*"
tags-ignore: "*"
pull_request: ~
# FUTURE ENHANCEMENT(s):
# * install faster (see below)
# * use github.event.repository.name or ${GITHUB_REPOSITORY#*/} as the
# tarball/build name instead of Dist-To-Test
jobs:
build-tarball:
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- name: Check out repo
- uses: actions/checkout@v3
+ uses: actions/checkout@v4
- name: Install cpanminus
run: |
curl https://cpanmin.us/ > /tmp/cpanm
chmod u+x /tmp/cpanm
- name: Install Dist::Zilla
run: sudo apt-get install -y libdist-zilla-perl
- name: Install prereqs
# This could probably be made more efficient by looking at what it's
# installing via cpanm that could, instead, be installed from apt. I
# may do that later, but for now, it's fine! -- rjbs, 2023-01-07
run: |
dzil authordeps --missing > /tmp/deps-phase-1.txt
/tmp/cpanm --notest -S < /tmp/deps-phase-1.txt
dzil listdeps --author --missing >> /tmp/deps-phase-2.txt
/tmp/cpanm --notest -S < /tmp/deps-phase-2.txt
- name: Build tarball
run: |
dzil build --in Dist-To-Test
tar zcvf Dist-To-Test.tar.gz Dist-To-Test
- name: Upload tarball
- uses: actions/upload-artifact@v3
+ uses: actions/upload-artifact@v4
with:
name: Dist-To-Test.tar.gz
path: Dist-To-Test.tar.gz
multiperl-test:
needs: build-tarball
env:
# some plugins still needs this to run their tests...
PERL_USE_UNSAFE_INC: 0
AUTHOR_TESTING: 1
AUTOMATED_TESTING: 1
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version: [ "devel", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Download tarball
- uses: actions/download-artifact@v3
+ uses: actions/download-artifact@v4
with:
name: Dist-To-Test.tar.gz
- name: Extract tarball
run: tar zxvf Dist-To-Test.tar.gz
- name: Install dependencies
working-directory: ./Dist-To-Test
run: cpanm --installdeps --notest .
- name: Makefile.PL
working-directory: ./Dist-To-Test
run: perl Makefile.PL
- name: Install yath
run: cpanm --notest Test2::Harness
- name: Install testing libraries
run: cpanm --notest Test2::Harness::Renderer::JUnit
- name: Run the tests
working-directory: ./Dist-To-Test
run: |
JUNIT_TEST_FILE="/tmp/test-output.xml" ALLOW_PASSING_TODOS=1 yath test --renderer=Formatter --renderer=JUnit -D
- name: Publish test report
uses: mikepenz/action-junit-report@v3
if: always() # always run even if the previous step fails
with:
check_name: JUnit Report (${{ matrix.perl-version }})
report_paths: /tmp/test-output.xml
|
rjbs/Dist-Zilla
|
0bad3f529d231fd18b3511064b982f6bfa81178c
|
copy relevant docs from [Git::GatherDir] to here
|
diff --git a/lib/Dist/Zilla/Plugin/GatherDir.pm b/lib/Dist/Zilla/Plugin/GatherDir.pm
index 90353e6..9a49f72 100644
--- a/lib/Dist/Zilla/Plugin/GatherDir.pm
+++ b/lib/Dist/Zilla/Plugin/GatherDir.pm
@@ -1,248 +1,250 @@
package Dist::Zilla::Plugin::GatherDir;
# ABSTRACT: gather all the files in a directory
use Moose;
with 'Dist::Zilla::Role::FileGatherer';
use Dist::Zilla::Pragmas;
use namespace::autoclean;
use Dist::Zilla::Types qw(Path);
use Dist::Zilla::Util;
=head1 DESCRIPTION
This is a very, very simple L<FileGatherer|Dist::Zilla::Role::FileGatherer>
plugin. It looks in the directory named in the L</root> attribute and adds all
the files it finds there. If the root begins with a tilde, the tilde is
passed through C<glob()> first.
Almost every dist will be built with one GatherDir plugin, since it's the
easiest way to get files from disk into your dist. Most users just need:
[GatherDir]
[PruneCruft]
...and this will pick up all the files from the current directory into the
dist. (L<PruneCruft|Dist::Zilla::Plugin::PruneCruft> is needed, here, to drop
files that might present as build artifacts, but should not be shipped.) You
can use it multiple times, as you can any other plugin, by providing a plugin
name. For example, if you want to include external specification files into a
subdir of your dist, you might write:
[GatherDir]
; this plugin needs no config and gathers most of your files
[GatherDir / SpecFiles]
; this plugin gets all the files in the root dir and adds them under ./spec
root = ~/projects/my-project/spec
prefix = spec
=cut
use File::Find::Rule;
use File::Spec;
use Path::Tiny;
use List::Util 1.33 'all';
=attr root
This is the directory in which to look for files. If not given, it defaults to
the dist root -- generally, the place where your F<dist.ini> or other
-configuration file is located.
+configuration file is located. It may begin with C<~> (or C<~user>)
+to mean your (or some other user's) home directory. If a relative path,
+it is relative to the dist root.
=cut
has root => (
is => 'ro',
isa => Path,
lazy => 1,
coerce => 1,
required => 1,
default => sub { shift->zilla->root },
);
=attr prefix
This parameter can be set to place the gathered files under a particular
directory. See the L<description|DESCRIPTION> above for an example.
=cut
has prefix => (
is => 'ro',
isa => 'Str',
default => '',
);
=attr include_dotfiles
By default, files will not be included if they begin with a dot. This goes
both for files and for directories relative to the C<root>.
In almost all cases, the default value (false) is correct.
=cut
has include_dotfiles => (
is => 'ro',
isa => 'Bool',
default => 0,
);
=attr follow_symlinks
By default, symlinks pointing to directories will not be followed; set
C<< follow_symlinks = 1 >> to traverse these links as if they were normal
directories.
In all followed directories, files which are symlinks are B<always> gathered,
with the link turning into a normal file.
=cut
has follow_symlinks => (
is => 'ro',
isa => 'Bool',
default => 0,
);
sub mvp_multivalue_args { qw(exclude_filename exclude_match prune_directory) }
=attr exclude_filename
To exclude certain files from being gathered, use the C<exclude_filename>
option. The filename is matched exactly, relative to C<root>.
This may be used multiple times to specify multiple files to exclude.
=cut
has exclude_filename => (
is => 'ro',
isa => 'ArrayRef',
default => sub { [] },
);
=attr exclude_match
This is just like C<exclude_filename> but provides a regular expression
pattern. Filenames matching the pattern (relative to C<root>) are not
gathered. This may be used
multiple times to specify multiple patterns to exclude.
=cut
has exclude_match => (
is => 'ro',
isa => 'ArrayRef',
default => sub { [] },
);
=attr prune_directory
While traversing, any directory matching the regular expression pattern will
not be traversed further. This may be used multiple times to specify multiple
directories to skip.
=cut
has prune_directory => (
is => 'ro',
isa => 'ArrayRef',
default => sub { [] },
);
around dump_config => sub {
my $orig = shift;
my $self = shift;
my $config = $self->$orig;
$config->{+__PACKAGE__} = {
prefix => $self->prefix,
# only report relative to dist root to avoid leaking private info
root => path($self->root)->relative($self->zilla->root),
(map { $_ => $self->$_ ? 1 : 0 } qw(include_dotfiles follow_symlinks)),
(map { $_ => [ sort @{ $self->$_ } ] } qw(exclude_filename exclude_match prune_directory)),
};
return $config;
};
sub gather_files {
my ($self) = @_;
my $exclude_regex = qr/\000/;
$exclude_regex = qr/(?:$exclude_regex)|$_/
for @{ $self->exclude_match };
my $repo_root = $self->zilla->root;
my $root = "" . $self->root;
$root =~ s{^~([\\/])}{ Dist::Zilla::Util->homedir . $1 }e;
$root = path($root)->absolute($repo_root)->stringify if path($root)->is_relative;
my $prune_regex = qr/\000/;
$prune_regex = qr/$prune_regex|$_/
for ( @{ $self->prune_directory },
$self->include_dotfiles ? () : ( qr/^\.[^.]/ ) );
# build up the rules
my $rule = File::Find::Rule->new();
$rule->extras({ follow => $self->follow_symlinks });
$rule->exec(sub { $self->log_debug('considering ' . path($_[-1])->relative($repo_root)); 1 })
if $self->zilla->logger->get_debug;
$rule->or(
$rule->new->directory->exec(sub { /$prune_regex/ })->prune->discard,
$rule->new,
);
if ($self->follow_symlinks) {
$rule->or(
$rule->new->file, # symlinks to files still count as files
$rule->new->symlink, # traverse into the linked dir, but screen it out later
);
} else {
$rule->file;
}
$rule->not_exec(sub { /^\.[^.]/ }) unless $self->include_dotfiles; # exec passes basename as $_
$rule->exec(sub {
my $relative = path($_[-1])->relative($root);
$relative !~ $exclude_regex &&
all { $relative ne $_ } @{ $self->exclude_filename }
});
FILE: for my $filename ($rule->in($root)) {
next if -d $filename;
# _file_from_filename is overloaded in GatherDir::Template
my $fileobj = $self->_file_from_filename($filename);
# GatherDir::Template may rename the file
$filename = $fileobj->name;
my $file = path($filename)->relative($root);
$file = path($self->prefix, $file) if $self->prefix;
$fileobj->name($file->stringify);
$self->add_file($fileobj);
}
return;
}
sub _file_from_filename {
my ($self, $filename) = @_;
my @stat = stat $filename or $self->log_fatal("$filename does not exist!");
return Dist::Zilla::File::OnDisk->new({
name => $filename,
mode => $stat[2] & 0755, # kill world-writeability
});
}
__PACKAGE__->meta->make_immutable;
1;
|
rjbs/Dist-Zilla
|
51b9c0352b8549602b4d4fb799a0e91a93c688aa
|
GitHub Action: rebuild workflower
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index 12b4876..d9e1345 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,94 +1,90 @@
name: "multiperl test"
-on: [ push, pull_request ]
+on:
+ push:
+ branches: "*"
+ tags-ignore: "*"
+ pull_request: ~
# FUTURE ENHANCEMENT(s):
# * install faster (see below)
# * use github.event.repository.name or ${GITHUB_REPOSITORY#*/} as the
# tarball/build name instead of Dist-To-Test
jobs:
build-tarball:
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- name: Check out repo
uses: actions/checkout@v3
- name: Install cpanminus
run: |
curl https://cpanmin.us/ > /tmp/cpanm
chmod u+x /tmp/cpanm
- name: Install Dist::Zilla
run: sudo apt-get install -y libdist-zilla-perl
- name: Install prereqs
# This could probably be made more efficient by looking at what it's
# installing via cpanm that could, instead, be installed from apt. I
# may do that later, but for now, it's fine! -- rjbs, 2023-01-07
run: |
- dzil authordeps --missing | /tmp/cpanm --notest -S
- dzil listdeps --author --missing | /tmp/cpanm --notest -S
+ dzil authordeps --missing > /tmp/deps-phase-1.txt
+ /tmp/cpanm --notest -S < /tmp/deps-phase-1.txt
+ dzil listdeps --author --missing >> /tmp/deps-phase-2.txt
+ /tmp/cpanm --notest -S < /tmp/deps-phase-2.txt
- name: Build tarball
run: |
dzil build --in Dist-To-Test
tar zcvf Dist-To-Test.tar.gz Dist-To-Test
- name: Upload tarball
uses: actions/upload-artifact@v3
with:
name: Dist-To-Test.tar.gz
path: Dist-To-Test.tar.gz
multiperl-test:
needs: build-tarball
env:
# some plugins still needs this to run their tests...
PERL_USE_UNSAFE_INC: 0
AUTHOR_TESTING: 1
AUTOMATED_TESTING: 1
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
- perl-version:
- - 'latest'
- - '5.36'
- - '5.34'
- - '5.32'
- - '5.30'
- - '5.28'
- - '5.26'
- - '5.24'
- - '5.22'
- - '5.20'
+ perl-version: [ "devel", "5.36", "5.34", "5.32", "5.30", "5.28", "5.26", "5.24", "5.22", "5.20" ]
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Download tarball
uses: actions/download-artifact@v3
with:
name: Dist-To-Test.tar.gz
- name: Extract tarball
run: tar zxvf Dist-To-Test.tar.gz
- name: Install dependencies
working-directory: ./Dist-To-Test
run: cpanm --installdeps --notest .
- name: Makefile.PL
working-directory: ./Dist-To-Test
run: perl Makefile.PL
- name: Install yath
run: cpanm --notest Test2::Harness
- name: Install testing libraries
run: cpanm --notest Test2::Harness::Renderer::JUnit
- name: Run the tests
working-directory: ./Dist-To-Test
run: |
JUNIT_TEST_FILE="/tmp/test-output.xml" ALLOW_PASSING_TODOS=1 yath test --renderer=Formatter --renderer=JUnit -D
- name: Publish test report
uses: mikepenz/action-junit-report@v3
if: always() # always run even if the previous step fails
with:
check_name: JUnit Report (${{ matrix.perl-version }})
report_paths: /tmp/test-output.xml
|
rjbs/Dist-Zilla
|
e76e6482e48966e84e982769d3ca45ecbb204946
|
v6.031
|
diff --git a/Changes b/Changes
index 56680b0..6b12f7b 100644
--- a/Changes
+++ b/Changes
@@ -1,515 +1,517 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+
+6.031 2023-11-20 19:49:23-05:00 America/New_York
- avoid some warnings on platforms without symlinks; (thanks, reneeb!)
6.030 2023-01-18 21:36:40-05:00 America/New_York
- "dzil new" will use command line options before configuration
- "dzil add" now falls back to %Mint stash options before defaults
(for both of the above: thanks, Graham Knop!)
6.029 2022-11-25 17:02:33-05:00 America/New_York
- update some links to use https instead of http (thanks, Elvin
Aslanov)
- turn on strict and warnings in generated author tests (thanks, Mark
Flickinger)
- use "v1.2.3" for multi-dot versions in "package NAME VERSION" formats
(thanks, Branislav ZahradnÃk)
- fixes to operation on msys (thanks, Paulo Custodio)
- add "main_module" option to MakeMaker (thanks, Tatsuhiko Miyagawa)
- fix authordeps behavior; don't add an object to @INC (thanks, Shoichi
Kaji)
6.028 2022-11-09 10:54:14-05:00 America/New_York
- remove bogus work-in-progress signatures-using commit from 6.027;
that was a bad release! thanks for the heads-up about it to Gianni
"dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
|
rjbs/Dist-Zilla
|
8a44a27634505fc41b16a809e233baef96318099
|
Changes: update for symlink tweak
|
diff --git a/Changes b/Changes
index f403f9e..56680b0 100644
--- a/Changes
+++ b/Changes
@@ -1,515 +1,516 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+ - avoid some warnings on platforms without symlinks; (thanks, reneeb!)
6.030 2023-01-18 21:36:40-05:00 America/New_York
- "dzil new" will use command line options before configuration
- "dzil add" now falls back to %Mint stash options before defaults
(for both of the above: thanks, Graham Knop!)
6.029 2022-11-25 17:02:33-05:00 America/New_York
- update some links to use https instead of http (thanks, Elvin
Aslanov)
- turn on strict and warnings in generated author tests (thanks, Mark
Flickinger)
- use "v1.2.3" for multi-dot versions in "package NAME VERSION" formats
(thanks, Branislav ZahradnÃk)
- fixes to operation on msys (thanks, Paulo Custodio)
- add "main_module" option to MakeMaker (thanks, Tatsuhiko Miyagawa)
- fix authordeps behavior; don't add an object to @INC (thanks, Shoichi
Kaji)
6.028 2022-11-09 10:54:14-05:00 America/New_York
- remove bogus work-in-progress signatures-using commit from 6.027;
that was a bad release! thanks for the heads-up about it to Gianni
"dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
|
rjbs/Dist-Zilla
|
90266465da75b6ccf4179967486c5a4585516204
|
do not warn about 'uninitialized value' on non-symlink platforms
|
diff --git a/lib/Dist/Zilla/Dist/Builder.pm b/lib/Dist/Zilla/Dist/Builder.pm
index 15078bc..a58911b 100644
--- a/lib/Dist/Zilla/Dist/Builder.pm
+++ b/lib/Dist/Zilla/Dist/Builder.pm
@@ -270,617 +270,617 @@ sub _load_config {
my $root = $arg->{root};
require Dist::Zilla::MVP::Assembler::Zilla;
require Dist::Zilla::MVP::Section;
my $assembler = Dist::Zilla::MVP::Assembler::Zilla->new({
chrome => $arg->{chrome},
zilla_class => $class,
section_class => 'Dist::Zilla::MVP::Section', # make this DZMA default
});
for ($assembler->sequence->section_named('_')) {
$_->add_value(chrome => $arg->{chrome});
$_->add_value(root => $arg->{root});
$_->add_value(_global_stashes => $arg->{_global_stashes})
if $arg->{_global_stashes};
}
my $seq;
try {
$seq = $config_class->read_config(
$root->child('dist'),
{
assembler => $assembler
},
);
} catch {
die $_ unless try {
$_->isa('Config::MVP::Error')
and $_->ident eq 'package not installed'
};
my $package = $_->package;
my $bundle = $_->section_name =~ m{^@(?!.*/)} ? ' bundle' : '';
die <<"END_DIE";
Required plugin$bundle $package isn't installed.
Run 'dzil authordeps' to see a list of all required plugins.
You can pipe the list to your CPAN client to install or update them:
dzil authordeps --missing | cpanm
END_DIE
};
return $seq;
}
=method build_in
$zilla->build_in($root);
This method builds the distribution in the given directory. If no directory
name is given, it defaults to DistName-Version. If the distribution has
already been built, an exception will be thrown.
=method build
This method just calls C<build_in> with no arguments. It gets you the default
behavior without the weird-looking formulation of C<build_in> with no object
for the preposition!
=cut
sub build { $_[0]->build_in }
sub build_in {
my ($self, $root) = @_;
$self->log_fatal("tried to build with a minter")
if $self->isa('Dist::Zilla::Dist::Minter');
$self->log_fatal("attempted to build " . $self->name . " a second time")
if $self->built_in;
$_->before_build for @{ $self->plugins_with(-BeforeBuild) };
$self->log("beginning to build " . $self->name);
$_->gather_files for @{ $self->plugins_with(-FileGatherer) };
$_->set_file_encodings for @{ $self->plugins_with(-EncodingProvider) };
$_->prune_files for @{ $self->plugins_with(-FilePruner) };
$self->version; # instantiate this lazy attribute now that files are gathered
$_->munge_files for @{ $self->plugins_with(-FileMunger) };
$_->register_prereqs for @{ $self->plugins_with(-PrereqSource) };
$self->prereqs->finalize;
# Barf if someone has already set up a prereqs entry? -- rjbs, 2010-04-13
$self->distmeta->{prereqs} = $self->prereqs->as_string_hash;
$_->setup_installer for @{ $self->plugins_with(-InstallTool) };
$self->_check_dupe_files;
my $build_root = $self->_prep_build_root($root);
$self->log("writing " . $self->name . " in $build_root");
for my $file (@{ $self->files }) {
$self->_write_out_file($file, $build_root);
}
$_->after_build({ build_root => $build_root })
for @{ $self->plugins_with(-AfterBuild) };
$self->built_in($build_root);
}
=attr built_in
This is the L<Path::Tiny>, if any, in which the dist has been built.
=cut
has built_in => (
is => 'rw',
isa => Path,
init_arg => undef,
coerce => 1,
);
=method ensure_built_in
$zilla->ensure_built_in($root);
This method behaves like C<L</build_in>>, but if the dist is already built in
C<$root> (or the default root, if no root is given), no exception is raised.
=method ensure_built
This method just calls C<ensure_built_in> with no arguments. It gets you the
default behavior without the weird-looking formulation of C<ensure_built_in>
with no object for the preposition!
=cut
sub ensure_built {
$_[0]->ensure_built_in;
}
sub ensure_built_in {
my ($self, $root) = @_;
# $root ||= $self->name . q{-} . $self->version;
return $self->built_in if $self->built_in and
(!$root or ($self->built_in eq $root));
Carp::croak("dist is already built, but not in $root") if $self->built_in;
$self->build_in($root);
}
=method dist_basename
my $basename = $zilla->dist_basename;
This method will return the dist's basename (e.g. C<Dist-Name-1.01>.
The basename is used as the top-level directory in the tarball. It
does not include C<-TRIAL>, even if building a trial dist.
=cut
sub dist_basename {
my ($self) = @_;
return join(q{},
$self->name,
'-',
$self->version,
);
}
=method archive_basename
my $basename = $zilla->archive_basename;
This method will return the filename, without the format extension
(e.g. C<Dist-Name-1.01> or C<Dist-Name-1.01-TRIAL>).
=cut
sub archive_basename {
my ($self) = @_;
return join q{},
$self->dist_basename,
( $self->is_trial && $self->version !~ /_/ ? '-TRIAL' : '' ),
;
}
=method archive_filename
my $tarball = $zilla->archive_filename;
This method will return the filename (e.g. C<Dist-Name-1.01.tar.gz>)
of the tarball of this distribution. It will include C<-TRIAL> if building a
trial distribution, unless the version contains an underscore. The tarball
might not exist.
=cut
sub archive_filename {
my ($self) = @_;
return join q{}, $self->archive_basename, '.tar.gz';
}
=method build_archive
$zilla->build_archive;
This method will ensure that the dist has been built, and will then build a
tarball of the build directory in the current directory.
=cut
sub build_archive {
my ($self) = @_;
my $built_in = $self->ensure_built;
my $basedir = path($self->dist_basename);
$_->before_archive for $self->plugins_with(-BeforeArchive)->@*;
for my $builder ($self->plugins_with(-ArchiveBuilder)->@*) {
my $file = $builder->build_archive($self->archive_basename, $built_in, $basedir);
return $file if defined $file;
}
my $method = eval { +require Archive::Tar::Wrapper;
Archive::Tar::Wrapper->VERSION('0.15'); 1 }
? '_build_archive_with_wrapper'
: '_build_archive';
my $archive = $self->$method($built_in, $basedir);
my $file = path($self->archive_filename);
$self->log("writing archive to $file");
$archive->write("$file", 9);
return $file;
}
sub _build_archive {
my ($self, $built_in, $basedir) = @_;
$self->log("building archive with Archive::Tar; install Archive::Tar::Wrapper 0.15 or newer for improved speed");
require Archive::Tar;
my $archive = Archive::Tar->new;
my %seen_dir;
for my $distfile (
sort { length($a->name) <=> length($b->name) } @{ $self->files }
) {
my $in = path($distfile->name)->parent;
unless ($seen_dir{ $in }++) {
$archive->add_data(
$basedir->child($in),
'',
{ type => Archive::Tar::Constant::DIR(), mode => 0755 },
)
}
my $filename = $built_in->child( $distfile->name );
$archive->add_data(
$basedir->child( $distfile->name ),
path($filename)->slurp_raw,
{ mode => (stat $filename)[2] & ~022 },
);
}
return $archive;
}
sub _build_archive_with_wrapper {
my ($self, $built_in, $basedir) = @_;
$self->log("building archive with Archive::Tar::Wrapper");
my $archive = Archive::Tar::Wrapper->new;
for my $distfile (
sort { length($a->name) <=> length($b->name) } @{ $self->files }
) {
my $in = path($distfile->name)->parent;
my $filename = $built_in->child( $distfile->name );
$archive->add(
$basedir->child( $distfile->name )->stringify,
$filename->stringify,
{ perm => (stat $filename)[2] & ~022 },
);
}
return $archive;
}
sub _prep_build_root {
my ($self, $build_root) = @_;
$build_root = path($build_root || $self->dist_basename);
$build_root->mkpath unless -d $build_root;
my $dist_root = $self->root;
return $build_root if !-d $build_root;
my $ok = eval { $build_root->remove_tree({ safe => 0 }); 1 };
die "unable to delete '$build_root' in preparation of build: $@" unless $ok;
# the following is done only on windows, and only if the deletion failed,
# yet rmtree reported success, because currently rmdir is non-blocking as per:
# https://rt.perl.org/Ticket/Display.html?id=123958
if ( $^O eq 'MSWin32' and -d $build_root ) {
$self->log("spinning for at least one second to allow other processes to release locks on $build_root");
my $timeout = time + 2;
while(time != $timeout and -d $build_root) { }
die "unable to delete '$build_root' in preparation of build because some process has a lock on it"
if -d $build_root;
}
return $build_root;
}
=method release
$zilla->release;
This method releases the distribution, probably by uploading it to the CPAN.
The actual effects of this method (as with most of the methods) is determined
by the loaded plugins.
=cut
sub release {
my $self = shift;
Carp::croak("you can't release without any Releaser plugins")
unless my @releasers = @{ $self->plugins_with(-Releaser) };
$ENV{DZIL_RELEASING} = 1;
my $tgz = $self->build_archive;
# call all plugins implementing BeforeRelease role
$_->before_release($tgz) for @{ $self->plugins_with(-BeforeRelease) };
# do the actual release
$_->release($tgz) for @releasers;
# call all plugins implementing AfterRelease role
$_->after_release($tgz) for @{ $self->plugins_with(-AfterRelease) };
}
=method clean
This method removes temporary files and directories suspected to have been
produced by the Dist::Zilla build process. Specifically, it deletes the
F<.build> directory and any entity that starts with the dist name and a hyphen,
like matching the glob C<Your-Dist-*>.
=cut
sub clean {
my ($self, $dry_run) = @_;
require File::Path;
for my $x (grep { -e } '.build', glob($self->name . '-*')) {
if ($dry_run) {
$self->log("clean: would remove $x");
} else {
$self->log("clean: removing $x");
File::Path::rmtree($x);
}
};
}
=method ensure_built_in_tmpdir
$zilla->ensure_built_in_tmpdir;
This method will consistently build the distribution in a temporary
subdirectory. It will return the path for the temporary build location.
=cut
sub ensure_built_in_tmpdir {
my $self = shift;
require File::Temp;
my $build_root = path('.build');
$build_root->mkpath unless -d $build_root;
my $target = path( File::Temp::tempdir(DIR => $build_root) );
$self->log("building distribution under $target for installation");
my $os_has_symlinks = eval { symlink("",""); 1 };
my $previous;
my $latest;
if( $os_has_symlinks ) {
$previous = path( $build_root, 'previous' );
$latest = path( $build_root, 'latest' );
if( -l $previous ) {
$previous->remove
or $self->log("cannot remove old .build/previous link");
}
if( -l $latest ) {
rename $latest, $previous
or $self->log("cannot move .build/latest link to .build/previous");
}
symlink $target->basename, $latest
or $self->log('cannot create link .build/latest');
}
$self->ensure_built_in($target);
return ($target, $latest, $previous);
}
=method install
$zilla->install( \%arg );
This method installs the distribution locally. The distribution will be built
in a temporary subdirectory, then the process will change directory to that
subdir and an installer will be run.
Valid arguments are:
keep_build_dir - if true, don't rmtree the build dir, even if everything
seemed to work
install_command - the command to run in the subdir to install the dist
default (roughly): $^X -MCPAN -einstall .
this argument should be an arrayref
=cut
sub install {
my ($self, $arg) = @_;
$arg ||= {};
my ($target, $latest) = $self->ensure_built_in_tmpdir;
my $ok = eval {
## no critic Punctuation
my $wd = File::pushd::pushd($target);
my @cmd = $arg->{install_command}
? @{ $arg->{install_command} }
: (cpanm => ".");
$self->log_debug([ 'installing via %s', \@cmd ]);
system(@cmd) && $self->log_fatal([ "error running %s", \@cmd ]);
1;
};
unless ($ok) {
my $error = $@ || '(exception clobered)';
$self->log("install failed, left failed dist in place at $target");
die $error;
}
if ($arg->{keep_build_dir}) {
$self->log("all's well; left dist in place at $target");
} else {
$self->log("all's well; removing $target");
$target->remove_tree({ safe => 0 });
$latest->remove_tree({ safe => 0 }) if -d $latest; # error cannot unlink, is a directory
$latest->remove if $latest;
}
return;
}
=method test
$zilla->test(\%arg);
This method builds a new copy of the distribution and tests it using
C<L</run_tests_in>>.
C<\%arg> may be omitted. Otherwise, valid arguments are:
keep_build_dir - if true, don't rmtree the build dir, even if everything
seemed to work
=cut
sub test {
my ($self, $arg) = @_;
Carp::croak("you can't test without any TestRunner plugins")
unless my @testers = @{ $self->plugins_with(-TestRunner) };
my ($target, $latest) = $self->ensure_built_in_tmpdir;
my $error = $self->run_tests_in($target, $arg);
if ($arg and $arg->{keep_build_dir}) {
$self->log("all's well; left dist in place at $target");
return;
}
$self->log("all's well; removing $target");
$target->remove_tree({ safe => 0 });
- $latest->remove_tree({ safe => 0 }) if -d $latest; # error cannot unlink, is a directory
+ $latest->remove_tree({ safe => 0 }) if $latest && -d $latest; # error cannot unlink, is a directory
$latest->remove if $latest;
}
=method run_tests_in
my $error = $zilla->run_tests_in($directory, $arg);
This method runs the tests in $directory (a Path::Tiny), which must contain an
already-built copy of the distribution. It will throw an exception if there
are test failures.
It does I<not> set any of the C<*_TESTING> environment variables, nor
does it clean up C<$directory> afterwards.
=cut
sub run_tests_in {
my ($self, $target, $arg) = @_;
Carp::croak("you can't test without any TestRunner plugins")
unless my @testers = @{ $self->plugins_with(-TestRunner) };
for my $tester (@testers) {
my $wd = File::pushd::pushd($target);
$tester->test( $target, $arg );
}
}
=method run_in_build
$zilla->run_in_build( \@cmd );
This method makes a temporary directory, builds the distribution there,
executes all the dist's L<BuildRunner|Dist::Zilla::Role::BuildRunner>s
(unless directed not to, via C<< $arg->{build} = 0 >>), and
then runs the given command in the build directory. If the command exits
non-zero, the directory will be left in place.
=cut
sub run_in_build {
my ($self, $cmd, $arg) = @_;
$self->log_fatal("you can't build without any BuildRunner plugins")
unless ($arg and exists $arg->{build} and ! $arg->{build})
or @{ $self->plugins_with(-BuildRunner) };
require "Config.pm"; # skip autoprereq
my ($target, $latest) = $self->ensure_built_in_tmpdir;
my $abstarget = $target->absolute;
# building the dist for real
my $ok = eval {
my $wd = File::pushd::pushd($target);
if ($arg and exists $arg->{build} and ! $arg->{build}) {
system(@$cmd) and die "error while running: @$cmd";
return 1;
}
$self->_ensure_blib;
local $ENV{PERL5LIB} = join $Config::Config{path_sep},
(map { $abstarget->child('blib', $_) } qw(arch lib)),
(defined $ENV{PERL5LIB} ? $ENV{PERL5LIB} : ());
local $ENV{PATH} = join $Config::Config{path_sep},
(map { $abstarget->child('blib', $_) } qw(bin script)),
(defined $ENV{PATH} ? $ENV{PATH} : ());
system(@$cmd) and die "error while running: @$cmd";
1;
};
if ($ok) {
$self->log("all's well; removing $target");
$target->remove_tree({ safe => 0 });
$latest->remove_tree({ safe => 0 }) if -d $latest; # error cannot unlink, is a directory
$latest->remove if $latest;
} else {
my $error = $@ || '(unknown error)';
$self->log($error);
$self->log_fatal("left failed dist in place at $target");
}
}
# Ensures that a F<blib> directory exists in the build, by invoking all
# C<-BuildRunner> plugins to generate it. Useful for commands that operate on
# F<blib>, such as C<test> or C<run>.
sub _ensure_blib {
my ($self) = @_;
unless ( -d 'blib' ) {
my @builders = @{ $self->plugins_with( -BuildRunner ) };
$self->log_fatal("no BuildRunner plugins specified") unless @builders;
$_->build for @builders;
$self->log_fatal("no blib; failed to build properly?") unless -d 'blib';
}
}
__PACKAGE__->meta->make_immutable;
1;
|
rjbs/Dist-Zilla
|
a8f9f8c2d3229193306d8d799e0bc81af2934478
|
v6.030
|
diff --git a/Changes b/Changes
index 2675bf7..f403f9e 100644
--- a/Changes
+++ b/Changes
@@ -1,515 +1,517 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+
+6.030 2023-01-18 21:36:40-05:00 America/New_York
- "dzil new" will use command line options before configuration
- "dzil add" now falls back to %Mint stash options before defaults
(for both of the above: thanks, Graham Knop!)
6.029 2022-11-25 17:02:33-05:00 America/New_York
- update some links to use https instead of http (thanks, Elvin
Aslanov)
- turn on strict and warnings in generated author tests (thanks, Mark
Flickinger)
- use "v1.2.3" for multi-dot versions in "package NAME VERSION" formats
(thanks, Branislav ZahradnÃk)
- fixes to operation on msys (thanks, Paulo Custodio)
- add "main_module" option to MakeMaker (thanks, Tatsuhiko Miyagawa)
- fix authordeps behavior; don't add an object to @INC (thanks, Shoichi
Kaji)
6.028 2022-11-09 10:54:14-05:00 America/New_York
- remove bogus work-in-progress signatures-using commit from 6.027;
that was a bad release! thanks for the heads-up about it to Gianni
"dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
|
rjbs/Dist-Zilla
|
79dbd8df7f7696b5efe108cf0ef93bff0cf6b62c
|
Changelog for "dzil add" and "dzil new" changes
|
diff --git a/Changes b/Changes
index fa543e0..2675bf7 100644
--- a/Changes
+++ b/Changes
@@ -1,515 +1,518 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+ - "dzil new" will use command line options before configuration
+ - "dzil add" now falls back to %Mint stash options before defaults
+ (for both of the above: thanks, Graham Knop!)
6.029 2022-11-25 17:02:33-05:00 America/New_York
- update some links to use https instead of http (thanks, Elvin
Aslanov)
- turn on strict and warnings in generated author tests (thanks, Mark
Flickinger)
- use "v1.2.3" for multi-dot versions in "package NAME VERSION" formats
(thanks, Branislav ZahradnÃk)
- fixes to operation on msys (thanks, Paulo Custodio)
- add "main_module" option to MakeMaker (thanks, Tatsuhiko Miyagawa)
- fix authordeps behavior; don't add an object to @INC (thanks, Shoichi
Kaji)
6.028 2022-11-09 10:54:14-05:00 America/New_York
- remove bogus work-in-progress signatures-using commit from 6.027;
that was a bad release! thanks for the heads-up about it to Gianni
"dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
4.300039 2013-09-20 06:05:10 Asia/Tokyo
- tweak metafile generator to keep CPAN::Meta validator happy (thanks,
|
rjbs/Dist-Zilla
|
ac13294c2cd22b9c5eb1eb1ca47a10e4545f27fb
|
make dzil new options options take priority over config
|
diff --git a/lib/Dist/Zilla/App/Command/new.pm b/lib/Dist/Zilla/App/Command/new.pm
index e991046..c6afdba 100644
--- a/lib/Dist/Zilla/App/Command/new.pm
+++ b/lib/Dist/Zilla/App/Command/new.pm
@@ -1,98 +1,98 @@
package Dist::Zilla::App::Command::new;
# ABSTRACT: mint a new dist
use Dist::Zilla::Pragmas;
use Dist::Zilla::App -command;
=head1 SYNOPSIS
Creates a new Dist-Zilla based distribution under the current directory.
$ dzil new Main::Module::Name
There are two arguments, C<-p> and C<-P>. C<-P> specify the minting profile
provider and C<-p> - the profile name.
The default profile provider first looks in the
F<~/.dzil/profiles/$profile_name> and then among standard profiles, shipped
with Dist::Zilla. For example:
$ dzil new -p work Corporate::Library
This command would instruct C<dzil> to look in F<~/.dzil/profiles/work> for a
F<profile.ini> (or other "profile" config file). If no profile name is given,
C<dzil> will look for the C<default> profile. If no F<default> directory
exists, it will use a very simple configuration shipped with Dist::Zilla.
$ dzil new -P Foo Corporate::Library
This command would instruct C<dzil> to consult the Foo provider about the
directory of 'default' profile.
Furthermore, it is possible to specify the default minting provider and profile
in the F<~/.dzil/config.ini> file, for example:
[%Mint]
provider = FooCorp
profile = work
=cut
sub abstract { 'mint a new dist' }
sub usage_desc { '%c new %o <ModuleName>' }
sub opt_spec {
- [ 'profile|p=s', 'name of the profile to use',
- { default => 'default' } ],
+ [ 'profile|p=s', 'name of the profile to use' ],
- [ 'provider|P=s', 'name of the profile provider to use',
- { default => 'Default' } ],
+ [ 'provider|P=s', 'name of the profile provider to use' ],
# [ 'module|m=s@', 'module(s) to create; may be given many times' ],
}
sub validate_args {
my ($self, $opt, $args) = @_;
require MooseX::Types::Perl;
$self->usage_error('dzil new takes exactly one argument') if @$args != 1;
my $name = $args->[0];
$name =~ s/::/-/g if MooseX::Types::Perl::is_ModuleName($name)
and not MooseX::Types::Perl::is_DistName($name);
$self->usage_error("$name is not a valid distribution name")
unless MooseX::Types::Perl::is_DistName($name);
$args->[0] = $name;
}
sub execute {
my ($self, $opt, $arg) = @_;
my $dist = $arg->[0];
- require Dist::Zilla::Dist::Minter;
my $stash = $self->app->_build_global_stashes;
+ my $mint_stash = $stash->{'%Mint'};
+
+ my $provider = $opt->provider // ($mint_stash && $mint_stash->provider) // 'Default';
+ my $profile = $opt->profile // ($mint_stash && $mint_stash->profile) // 'default';
+
+ require Dist::Zilla::Dist::Minter;
my $minter = Dist::Zilla::Dist::Minter->_new_from_profile(
- ( exists $stash->{'%Mint'} ?
- [ $stash->{'%Mint'}->provider, $stash->{'%Mint'}->profile ] :
- [ $opt->provider, $opt->profile ]
- ),
+ [ $provider, $profile ],
{
chrome => $self->app->chrome,
name => $dist,
_global_stashes => $stash,
},
);
$minter->mint_dist({
# modules => $opt->module,
});
}
1;
|
rjbs/Dist-Zilla
|
8121d9b227b3f1f281e23be5e6e5429f089dca5b
|
dzil add: follow %Mint config if no options given
|
diff --git a/lib/Dist/Zilla/App/Command/add.pm b/lib/Dist/Zilla/App/Command/add.pm
index e2c4a24..056b101 100644
--- a/lib/Dist/Zilla/App/Command/add.pm
+++ b/lib/Dist/Zilla/App/Command/add.pm
@@ -1,81 +1,89 @@
package Dist::Zilla::App::Command::add;
# ABSTRACT: add a module to a dist
use Dist::Zilla::Pragmas;
use Dist::Zilla::App -command;
use Dist::Zilla::Path;
use namespace::autoclean;
=head1 SYNOPSIS
Adds a new module to a Dist::Zilla-based distribution
$ dzil add Some::New::Module
There are two arguments, C<-p> and C<-P>. C<-P> specify the minting profile
provider and C<-p> - the profile name. These work just like C<dzil new>.
=cut
sub abstract { 'add modules to an existing dist' }
sub usage_desc { '%c %o <ModuleName>' }
sub opt_spec {
- [ 'profile|p=s', 'name of the profile to use',
- { default => 'default' } ],
+ [ 'profile|p=s', 'name of the profile to use' ],
- [ 'provider|P=s', 'name of the profile provider to use',
- { default => 'Default' } ],
+ [ 'provider|P=s', 'name of the profile provider to use' ],
# [ 'module|m=s@', 'module(s) to create; may be given many times' ],
}
sub validate_args {
my ($self, $opt, $args) = @_;
require MooseX::Types::Perl;
$self->usage_error('dzil add takes one or more arguments') if @$args < 1;
for my $name ( @$args ) {
$self->usage_error("$name is not a valid module name")
unless MooseX::Types::Perl::is_ModuleName($name);
}
}
sub execute {
my ($self, $opt, $arg) = @_;
my $zilla = $self->zilla;
my $dist = $zilla->name;
-
+
require File::pushd;
+ my $mint_stash = $zilla->stash_named('%Mint');
+
+ my $provider = $opt->provider
+ // ($mint_stash && $mint_stash->provider)
+ // 'Default';
+
+ my $profile = $opt->profile
+ // ($mint_stash && $mint_stash->profile)
+ // 'default';
+
require Dist::Zilla::Dist::Minter;
my $minter = Dist::Zilla::Dist::Minter->_new_from_profile(
- [ $opt->provider, $opt->profile ],
+ [ $provider, $profile ],
{
chrome => $self->app->chrome,
name => $dist,
_global_stashes => $self->app->_build_global_stashes,
},
);
my $root = path($zilla->root)->absolute;
my $wd = File::pushd::pushd($minter->root);
my $factory = $minter->plugin_named(':DefaultModuleMaker');
for my $name ( @$arg ) {
$factory->make_module({ name => $name });
}
for my $file ( @{ $factory->zilla->files} ) {
$zilla->_write_out_file($file, $root);
}
}
1;
|
rjbs/Dist-Zilla
|
70e5e341becfd734e2010b3d0028b9aeff60851e
|
GitHub Actions: also run on pull requests
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index fa878dd..12b4876 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,94 +1,94 @@
name: "multiperl test"
-on: push
+on: [ push, pull_request ]
# FUTURE ENHANCEMENT(s):
# * install faster (see below)
# * use github.event.repository.name or ${GITHUB_REPOSITORY#*/} as the
# tarball/build name instead of Dist-To-Test
jobs:
build-tarball:
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- name: Check out repo
uses: actions/checkout@v3
- name: Install cpanminus
run: |
curl https://cpanmin.us/ > /tmp/cpanm
chmod u+x /tmp/cpanm
- name: Install Dist::Zilla
run: sudo apt-get install -y libdist-zilla-perl
- name: Install prereqs
# This could probably be made more efficient by looking at what it's
# installing via cpanm that could, instead, be installed from apt. I
# may do that later, but for now, it's fine! -- rjbs, 2023-01-07
run: |
dzil authordeps --missing | /tmp/cpanm --notest -S
dzil listdeps --author --missing | /tmp/cpanm --notest -S
- name: Build tarball
run: |
dzil build --in Dist-To-Test
tar zcvf Dist-To-Test.tar.gz Dist-To-Test
- name: Upload tarball
uses: actions/upload-artifact@v3
with:
name: Dist-To-Test.tar.gz
path: Dist-To-Test.tar.gz
multiperl-test:
needs: build-tarball
env:
# some plugins still needs this to run their tests...
PERL_USE_UNSAFE_INC: 0
AUTHOR_TESTING: 1
AUTOMATED_TESTING: 1
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version:
- 'latest'
- '5.36'
- '5.34'
- '5.32'
- '5.30'
- '5.28'
- '5.26'
- '5.24'
- '5.22'
- '5.20'
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Download tarball
uses: actions/download-artifact@v3
with:
name: Dist-To-Test.tar.gz
- name: Extract tarball
run: tar zxvf Dist-To-Test.tar.gz
- name: Install dependencies
working-directory: ./Dist-To-Test
run: cpanm --installdeps --notest .
- name: Makefile.PL
working-directory: ./Dist-To-Test
run: perl Makefile.PL
- name: Install yath
run: cpanm --notest Test2::Harness
- name: Install testing libraries
run: cpanm --notest Test2::Harness::Renderer::JUnit
- name: Run the tests
working-directory: ./Dist-To-Test
run: |
JUNIT_TEST_FILE="/tmp/test-output.xml" ALLOW_PASSING_TODOS=1 yath test --renderer=Formatter --renderer=JUnit -D
- name: Publish test report
uses: mikepenz/action-junit-report@v3
if: always() # always run even if the previous step fails
with:
check_name: JUnit Report (${{ matrix.perl-version }})
report_paths: /tmp/test-output.xml
|
rjbs/Dist-Zilla
|
dea89e2aaa37d179fd3da643a507f801a1032dbb
|
GitHub Actions: put perl version in report name
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index d80eb8b..fa878dd 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,93 +1,94 @@
name: "multiperl test"
on: push
# FUTURE ENHANCEMENT(s):
# * install faster (see below)
# * use github.event.repository.name or ${GITHUB_REPOSITORY#*/} as the
# tarball/build name instead of Dist-To-Test
jobs:
build-tarball:
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- name: Check out repo
uses: actions/checkout@v3
- name: Install cpanminus
run: |
curl https://cpanmin.us/ > /tmp/cpanm
chmod u+x /tmp/cpanm
- name: Install Dist::Zilla
run: sudo apt-get install -y libdist-zilla-perl
- name: Install prereqs
# This could probably be made more efficient by looking at what it's
# installing via cpanm that could, instead, be installed from apt. I
# may do that later, but for now, it's fine! -- rjbs, 2023-01-07
run: |
dzil authordeps --missing | /tmp/cpanm --notest -S
dzil listdeps --author --missing | /tmp/cpanm --notest -S
- name: Build tarball
run: |
dzil build --in Dist-To-Test
tar zcvf Dist-To-Test.tar.gz Dist-To-Test
- name: Upload tarball
uses: actions/upload-artifact@v3
with:
name: Dist-To-Test.tar.gz
path: Dist-To-Test.tar.gz
multiperl-test:
needs: build-tarball
env:
# some plugins still needs this to run their tests...
PERL_USE_UNSAFE_INC: 0
AUTHOR_TESTING: 1
AUTOMATED_TESTING: 1
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version:
- 'latest'
- '5.36'
- '5.34'
- '5.32'
- '5.30'
- '5.28'
- '5.26'
- '5.24'
- '5.22'
- '5.20'
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Download tarball
uses: actions/download-artifact@v3
with:
name: Dist-To-Test.tar.gz
- name: Extract tarball
run: tar zxvf Dist-To-Test.tar.gz
- name: Install dependencies
working-directory: ./Dist-To-Test
run: cpanm --installdeps --notest .
- name: Makefile.PL
working-directory: ./Dist-To-Test
run: perl Makefile.PL
- name: Install yath
run: cpanm --notest Test2::Harness
- name: Install testing libraries
run: cpanm --notest Test2::Harness::Renderer::JUnit
- name: Run the tests
working-directory: ./Dist-To-Test
run: |
JUNIT_TEST_FILE="/tmp/test-output.xml" ALLOW_PASSING_TODOS=1 yath test --renderer=Formatter --renderer=JUnit -D
- name: Publish test report
uses: mikepenz/action-junit-report@v3
if: always() # always run even if the previous step fails
with:
+ check_name: JUnit Report (${{ matrix.perl-version }})
report_paths: /tmp/test-output.xml
|
rjbs/Dist-Zilla
|
8e6aadcd0124abab984117854d93df320ee2d62d
|
GitHub Actions: prune the list of perl versions we test
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
index c90c5c9..d80eb8b 100644
--- a/.github/workflows/multiperl-test.yml
+++ b/.github/workflows/multiperl-test.yml
@@ -1,97 +1,93 @@
name: "multiperl test"
on: push
# FUTURE ENHANCEMENT(s):
# * install faster (see below)
# * use github.event.repository.name or ${GITHUB_REPOSITORY#*/} as the
# tarball/build name instead of Dist-To-Test
jobs:
build-tarball:
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- name: Check out repo
uses: actions/checkout@v3
- name: Install cpanminus
run: |
curl https://cpanmin.us/ > /tmp/cpanm
chmod u+x /tmp/cpanm
- name: Install Dist::Zilla
run: sudo apt-get install -y libdist-zilla-perl
- name: Install prereqs
# This could probably be made more efficient by looking at what it's
# installing via cpanm that could, instead, be installed from apt. I
# may do that later, but for now, it's fine! -- rjbs, 2023-01-07
run: |
dzil authordeps --missing | /tmp/cpanm --notest -S
dzil listdeps --author --missing | /tmp/cpanm --notest -S
- name: Build tarball
run: |
dzil build --in Dist-To-Test
tar zcvf Dist-To-Test.tar.gz Dist-To-Test
- name: Upload tarball
uses: actions/upload-artifact@v3
with:
name: Dist-To-Test.tar.gz
path: Dist-To-Test.tar.gz
multiperl-test:
needs: build-tarball
env:
# some plugins still needs this to run their tests...
PERL_USE_UNSAFE_INC: 0
AUTHOR_TESTING: 1
AUTOMATED_TESTING: 1
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
perl-version:
- 'latest'
- '5.36'
- '5.34'
- '5.32'
- '5.30'
- '5.28'
- '5.26'
- '5.24'
- '5.22'
- '5.20'
- - '5.18'
- - '5.16'
- - '5.14'
- - '5.12'
container:
image: perldocker/perl-tester:${{ matrix.perl-version }}
steps:
- name: Download tarball
uses: actions/download-artifact@v3
with:
name: Dist-To-Test.tar.gz
- name: Extract tarball
run: tar zxvf Dist-To-Test.tar.gz
- name: Install dependencies
working-directory: ./Dist-To-Test
run: cpanm --installdeps --notest .
- name: Makefile.PL
working-directory: ./Dist-To-Test
run: perl Makefile.PL
- name: Install yath
run: cpanm --notest Test2::Harness
- name: Install testing libraries
run: cpanm --notest Test2::Harness::Renderer::JUnit
- name: Run the tests
working-directory: ./Dist-To-Test
run: |
JUNIT_TEST_FILE="/tmp/test-output.xml" ALLOW_PASSING_TODOS=1 yath test --renderer=Formatter --renderer=JUnit -D
- name: Publish test report
uses: mikepenz/action-junit-report@v3
if: always() # always run even if the previous step fails
with:
report_paths: /tmp/test-output.xml
|
rjbs/Dist-Zilla
|
7e33ec76df53409bbf14498b9eb4382106184ba1
|
Travis is long gone; use GitHub Actions
|
diff --git a/.github/workflows/multiperl-test.yml b/.github/workflows/multiperl-test.yml
new file mode 100644
index 0000000..c90c5c9
--- /dev/null
+++ b/.github/workflows/multiperl-test.yml
@@ -0,0 +1,97 @@
+name: "multiperl test"
+on: push
+
+# FUTURE ENHANCEMENT(s):
+# * install faster (see below)
+# * use github.event.repository.name or ${GITHUB_REPOSITORY#*/} as the
+# tarball/build name instead of Dist-To-Test
+
+jobs:
+ build-tarball:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ steps:
+ - name: Check out repo
+ uses: actions/checkout@v3
+ - name: Install cpanminus
+ run: |
+ curl https://cpanmin.us/ > /tmp/cpanm
+ chmod u+x /tmp/cpanm
+ - name: Install Dist::Zilla
+ run: sudo apt-get install -y libdist-zilla-perl
+ - name: Install prereqs
+ # This could probably be made more efficient by looking at what it's
+ # installing via cpanm that could, instead, be installed from apt. I
+ # may do that later, but for now, it's fine! -- rjbs, 2023-01-07
+ run: |
+ dzil authordeps --missing | /tmp/cpanm --notest -S
+ dzil listdeps --author --missing | /tmp/cpanm --notest -S
+ - name: Build tarball
+ run: |
+ dzil build --in Dist-To-Test
+ tar zcvf Dist-To-Test.tar.gz Dist-To-Test
+ - name: Upload tarball
+ uses: actions/upload-artifact@v3
+ with:
+ name: Dist-To-Test.tar.gz
+ path: Dist-To-Test.tar.gz
+
+ multiperl-test:
+ needs: build-tarball
+ env:
+ # some plugins still needs this to run their tests...
+ PERL_USE_UNSAFE_INC: 0
+ AUTHOR_TESTING: 1
+ AUTOMATED_TESTING: 1
+
+ runs-on: ubuntu-latest
+
+ strategy:
+ fail-fast: false
+ matrix:
+ perl-version:
+ - 'latest'
+ - '5.36'
+ - '5.34'
+ - '5.32'
+ - '5.30'
+ - '5.28'
+ - '5.26'
+ - '5.24'
+ - '5.22'
+ - '5.20'
+ - '5.18'
+ - '5.16'
+ - '5.14'
+ - '5.12'
+
+ container:
+ image: perldocker/perl-tester:${{ matrix.perl-version }}
+
+ steps:
+ - name: Download tarball
+ uses: actions/download-artifact@v3
+ with:
+ name: Dist-To-Test.tar.gz
+ - name: Extract tarball
+ run: tar zxvf Dist-To-Test.tar.gz
+ - name: Install dependencies
+ working-directory: ./Dist-To-Test
+ run: cpanm --installdeps --notest .
+ - name: Makefile.PL
+ working-directory: ./Dist-To-Test
+ run: perl Makefile.PL
+ - name: Install yath
+ run: cpanm --notest Test2::Harness
+ - name: Install testing libraries
+ run: cpanm --notest Test2::Harness::Renderer::JUnit
+ - name: Run the tests
+ working-directory: ./Dist-To-Test
+ run: |
+ JUNIT_TEST_FILE="/tmp/test-output.xml" ALLOW_PASSING_TODOS=1 yath test --renderer=Formatter --renderer=JUnit -D
+ - name: Publish test report
+ uses: mikepenz/action-junit-report@v3
+ if: always() # always run even if the previous step fails
+ with:
+ report_paths: /tmp/test-output.xml
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 2a34142..0000000
--- a/.travis.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-sudo: false
-language: perl
-perl:
- - blead # builds perl from git
- - dev # latest point release
- - "5.32"
- - "5.30"
- - "5.28"
- - "5.26"
- - "5.24"
- - "5.22"
- - "5.20"
-before_install:
- - git clone git://github.com/travis-perl/helpers ~/travis-perl-helpers
- - source ~/travis-perl-helpers/init
- - build-perl
- - perl -V
- - build-dist
- - cd $BUILD_DIR
-install:
- - cpan-install --deps
-script:
- - perl Makefile.PL
- - make
- - prove -b -r -s -j$(test-jobs) $(test-files)
|
rjbs/Dist-Zilla
|
cba51b6dab2aa6fb95e8c9f8244ba6810b08f39c
|
v6.029
|
diff --git a/Changes b/Changes
index b0939c4..fa543e0 100644
--- a/Changes
+++ b/Changes
@@ -1,515 +1,517 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+
+6.029 2022-11-25 17:02:33-05:00 America/New_York
- update some links to use https instead of http (thanks, Elvin
Aslanov)
- turn on strict and warnings in generated author tests (thanks, Mark
Flickinger)
- use "v1.2.3" for multi-dot versions in "package NAME VERSION" formats
(thanks, Branislav ZahradnÃk)
- fixes to operation on msys (thanks, Paulo Custodio)
- add "main_module" option to MakeMaker (thanks, Tatsuhiko Miyagawa)
- fix authordeps behavior; don't add an object to @INC (thanks, Shoichi
Kaji)
6.028 2022-11-09 10:54:14-05:00 America/New_York
- remove bogus work-in-progress signatures-using commit from 6.027;
that was a bad release! thanks for the heads-up about it to Gianni
"dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
4.300039 2013-09-20 06:05:10 Asia/Tokyo
- tweak metafile generator to keep CPAN::Meta validator happy (thanks,
David Golden)
|
rjbs/Dist-Zilla
|
9ea63be70bf2444a12415d9c377129cbafd0fb7c
|
Changes: credit for authordeps change
|
diff --git a/Changes b/Changes
index 3833a70..b0939c4 100644
--- a/Changes
+++ b/Changes
@@ -1,523 +1,525 @@
Revision history for {{$dist->name}}
{{$NEXT}}
- update some links to use https instead of http (thanks, Elvin
Aslanov)
- turn on strict and warnings in generated author tests (thanks, Mark
Flickinger)
- use "v1.2.3" for multi-dot versions in "package NAME VERSION" formats
(thanks, Branislav ZahradnÃk)
- fixes to operation on msys (thanks, Paulo Custodio)
- add "main_module" option to MakeMaker (thanks, Tatsuhiko Miyagawa)
+ - fix authordeps behavior; don't add an object to @INC (thanks, Shoichi
+ Kaji)
6.028 2022-11-09 10:54:14-05:00 America/New_York
- remove bogus work-in-progress signatures-using commit from 6.027;
that was a bad release! thanks for the heads-up about it to Gianni
"dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
4.300039 2013-09-20 06:05:10 Asia/Tokyo
- tweak metafile generator to keep CPAN::Meta validator happy (thanks,
David Golden)
4.300038 2013-09-08 09:18:34 America/New_York
- add horrible hack to avoid generating non-UTF-8 META.yml; seriously,
don't look at the code! Thanks, David Golden, whose code was simple
and probably much, much saner, but didn't cover as many cases as rjbs
wanted to cover.
4.300037 2013-08-28 21:43:36 America/New_York
- update repo and bugtacker URLs
4.300036 2013-08-25 21:41:21 America/New_York
|
rjbs/Dist-Zilla
|
eb3382ad685436401b728be39e73201ffaf66764
|
stringify Dist::Zilla::Path object before adding it to INC
|
diff --git a/lib/Dist/Zilla/Util/AuthorDeps.pm b/lib/Dist/Zilla/Util/AuthorDeps.pm
index 4aa0ad7..e960301 100644
--- a/lib/Dist/Zilla/Util/AuthorDeps.pm
+++ b/lib/Dist/Zilla/Util/AuthorDeps.pm
@@ -1,135 +1,135 @@
package Dist::Zilla::Util::AuthorDeps;
# ABSTRACT: Utils for listing your distribution's author dependencies
use Dist::Zilla::Pragmas;
use Dist::Zilla::Util;
use Path::Tiny;
use List::Util 1.45 ();
use namespace::autoclean;
sub format_author_deps {
my ($reqs, $versions) = @_;
my $formatted = '';
foreach my $rec (@{ $reqs }) {
my ($mod, $ver) = each(%{ $rec });
$formatted .= $versions ? "$mod = $ver\n" : "$mod\n";
}
chomp($formatted);
return $formatted;
}
sub extract_author_deps {
my ($root, $missing) = @_;
my $ini = path($root, 'dist.ini');
die "dzil authordeps only works on dist.ini files, and you don't have one\n"
unless -e $ini;
my $fh = $ini->openr_utf8;
require Config::INI::Reader;
my $config = Config::INI::Reader->read_handle($fh);
require CPAN::Meta::Requirements;
my $reqs = CPAN::Meta::Requirements->new;
if (defined (my $license = $config->{_}->{license})) {
$license = 'Software::License::'.$license;
$reqs->add_minimum($license => 0);
}
for my $section ( sort keys %$config ) {
if (q[_] eq $section) {
my $version = $config->{_}{':version'};
$reqs->add_minimum('Dist::Zilla' => $version) if $version;
next;
}
my $pack = $section;
$pack =~ s{\s*/.*$}{}; # trim optional space and slash-delimited suffix
my $version = 0;
$version = $config->{$section}->{':version'} if exists $config->{$section}->{':version'};
my $realname = Dist::Zilla::Util->expand_config_package_name($pack);
$reqs->add_minimum($realname => $version);
}
seek $fh, 0, 0;
my $in_filter = 0;
while (<$fh>) {
next unless $in_filter or /^\[\s*\@Filter/;
$in_filter = 0, next if /^\[/ and ! /^\[\s*\@Filter/;
$in_filter = 1;
next unless /\A-bundle\s*=\s*([^;\s]+)/;
my $pname = $1;
chomp($pname);
$reqs->add_minimum(Dist::Zilla::Util->expand_config_package_name($1) => 0)
}
seek $fh, 0, 0;
my @packages;
while (<$fh>) {
chomp;
next unless /\A\s*;\s*authordep\s*(\S+)\s*(?:=\s*([^;]+))?\s*/;
my $module = $1;
my $ver = $2 // "0";
$ver =~ s/\s+$//;
# Any "; authordep " is inserted at the beginning of the list
# in the file order so the user can control the order of at least a part of
# the plugin list
push @packages, $module;
# And added to the requirements so we can use it later
$reqs->add_string_requirement($module => $ver);
}
my $vermap = $reqs->as_string_hash;
# Add the other requirements
push(@packages, sort keys %{ $vermap });
# Move inc:: first in list as they may impact the loading of other
# plugins (in particular local ones).
# Also order inc:: so that those that want to hack @INC with inc:: plugins
# can have a consistent playground.
# We don't sort the others packages to preserve the same (random) ordering
# for the common case (no inc::, no '; authordep') as in previous dzil
# releases.
@packages = ((sort grep /^inc::/, @packages), (grep !/^inc::/, @packages));
@packages = List::Util::uniq(@packages);
if ($missing) {
require Module::Runtime;
@packages =
grep {
$_ eq 'perl'
? ! ($vermap->{perl} && eval "use $vermap->{perl}; 1")
: do {
my $m = $_;
! eval {
- local @INC = @INC; push @INC, $root;
+ local @INC = @INC; push @INC, "$root";
# This will die if module is missing
Module::Runtime::require_module($m);
my $v = $vermap->{$m};
# This will die if VERSION is too low
!$v || $m->VERSION($v);
# Success!
1
}
}
} @packages;
}
# Now that we have a sorted list of packages, use that to build an array of
# hashrefs for display.
[ map { { $_ => $vermap->{$_} } } @packages ]
}
1;
|
rjbs/Dist-Zilla
|
e538431594b1ddb4097e8124cf8a2a6b9e1a3dd8
|
Changes: credit for MakeMaker main_module
|
diff --git a/Changes b/Changes
index 0537bc3..3833a70 100644
--- a/Changes
+++ b/Changes
@@ -1,522 +1,523 @@
Revision history for {{$dist->name}}
{{$NEXT}}
- update some links to use https instead of http (thanks, Elvin
Aslanov)
- turn on strict and warnings in generated author tests (thanks, Mark
Flickinger)
- use "v1.2.3" for multi-dot versions in "package NAME VERSION" formats
(thanks, Branislav ZahradnÃk)
- fixes to operation on msys (thanks, Paulo Custodio)
+ - add "main_module" option to MakeMaker (thanks, Tatsuhiko Miyagawa)
6.028 2022-11-09 10:54:14-05:00 America/New_York
- remove bogus work-in-progress signatures-using commit from 6.027;
that was a bad release! thanks for the heads-up about it to Gianni
"dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
4.300039 2013-09-20 06:05:10 Asia/Tokyo
- tweak metafile generator to keep CPAN::Meta validator happy (thanks,
David Golden)
4.300038 2013-09-08 09:18:34 America/New_York
- add horrible hack to avoid generating non-UTF-8 META.yml; seriously,
don't look at the code! Thanks, David Golden, whose code was simple
and probably much, much saner, but didn't cover as many cases as rjbs
wanted to cover.
4.300037 2013-08-28 21:43:36 America/New_York
- update repo and bugtacker URLs
4.300036 2013-08-25 21:41:21 America/New_York
|
rjbs/Dist-Zilla
|
4f1c872024ea6a62b08eff2b2edaf470d4952a2c
|
Changes: credit for msys fixes
|
diff --git a/Changes b/Changes
index df32a3e..0537bc3 100644
--- a/Changes
+++ b/Changes
@@ -1,521 +1,522 @@
Revision history for {{$dist->name}}
{{$NEXT}}
- update some links to use https instead of http (thanks, Elvin
Aslanov)
- turn on strict and warnings in generated author tests (thanks, Mark
Flickinger)
- use "v1.2.3" for multi-dot versions in "package NAME VERSION" formats
(thanks, Branislav ZahradnÃk)
+ - fixes to operation on msys (thanks, Paulo Custodio)
6.028 2022-11-09 10:54:14-05:00 America/New_York
- remove bogus work-in-progress signatures-using commit from 6.027;
that was a bad release! thanks for the heads-up about it to Gianni
"dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
4.300039 2013-09-20 06:05:10 Asia/Tokyo
- tweak metafile generator to keep CPAN::Meta validator happy (thanks,
David Golden)
4.300038 2013-09-08 09:18:34 America/New_York
- add horrible hack to avoid generating non-UTF-8 META.yml; seriously,
don't look at the code! Thanks, David Golden, whose code was simple
and probably much, much saner, but didn't cover as many cases as rjbs
wanted to cover.
4.300037 2013-08-28 21:43:36 America/New_York
- update repo and bugtacker URLs
4.300036 2013-08-25 21:41:21 America/New_York
|
rjbs/Dist-Zilla
|
4c6f2f625c0684ae1d66c102c354704c9fdf3873
|
[MakeMaker] add main_module option
|
diff --git a/lib/Dist/Zilla/Plugin/MakeMaker.pm b/lib/Dist/Zilla/Plugin/MakeMaker.pm
index 102e7e4..6f65c0d 100644
--- a/lib/Dist/Zilla/Plugin/MakeMaker.pm
+++ b/lib/Dist/Zilla/Plugin/MakeMaker.pm
@@ -1,358 +1,375 @@
package Dist::Zilla::Plugin::MakeMaker;
# ABSTRACT: build a Makefile.PL that uses ExtUtils::MakeMaker
use Moose;
use Dist::Zilla::Pragmas;
use namespace::autoclean;
use Config;
use CPAN::Meta::Requirements 2.121; # requirements_for_module
use List::Util 1.29 qw(first pairs pairgrep);
use version;
use Dist::Zilla::File::InMemory;
use Dist::Zilla::Plugin::MakeMaker::Runner;
=head1 DESCRIPTION
This plugin will produce an L<ExtUtils::MakeMaker>-powered F<Makefile.PL> for
the distribution. If loaded, the L<Manifest|Dist::Zilla::Plugin::Manifest>
plugin should also be loaded.
=cut
=attr eumm_version
This option declares the version of ExtUtils::MakeMaker required to configure
and build the distribution. There is no default, although one may be added if
it can be determined that the generated F<Makefile.PL> requires some specific
minimum. I<No testing has been done on this front.>
=cut
has eumm_version => (
isa => 'Str',
is => 'rw',
);
=attr make_path
This option sets the path to F<make>, used to build your dist and run tests.
It defaults to the value for C<make> in L<Config>, or to C<make> if that isn't
set.
You probably won't need to set this option.
=cut
has 'make_path' => (
isa => 'Str',
is => 'ro',
default => $Config{make} || 'make',
);
+=attr main_module
+
+This option sets the name of the main module in your dist. It defaults to the
+name derived from the distribution's name after replacing C<-> with C<::>, (e.g.
+C<Foo::Bar> for distribution C<Foo-Bar>). The value is set as a C<NAME> argument
+for C<WriteMakefile>.
+
+You want to use this option when the name of distribution doesn't reflect any
+module names contained in your distribution e.g. C<LWP> vs C<libwww-perl>.
+
+=cut
+
+has main_module => (
+ isa => 'Str',
+ is => 'rw',
+);
+
=attr static_attribution
This option omits the version number in the "generated by"
comment in the Makefile.PL. For setups that copy the Makefile.PL
back to the repo, this avoids churn just from upgrading Dist::Zilla.
=cut
has 'static_attribution' => (
isa => 'Bool',
is => 'ro',
);
has '_runner' => (
is => 'ro',
lazy => 1,
handles => [qw(build test)],
default => sub {
my ($self) = @_;
Dist::Zilla::Plugin::MakeMaker::Runner->new({
zilla => $self->zilla,
plugin_name => $self->plugin_name . '::Runner',
make_path => $self->make_path,
default_jobs => $self->default_jobs,
});
},
);
# This is here, rather than at the top, so that the "build" and "test" methods
# will exist, as they are required by BuildRunner and TestRunner respectively.
# I had originally fixed this with stub methods, but stub methods do not behave
# properly with this use case until Moose 2.0300. -- rjbs, 2012-02-08
with qw(
Dist::Zilla::Role::BuildRunner
Dist::Zilla::Role::InstallTool
Dist::Zilla::Role::PrereqSource
Dist::Zilla::Role::FileGatherer
Dist::Zilla::Role::TestRunner
Dist::Zilla::Role::TextTemplate
);
my $template = q!# This file was automatically generated by {{ $generated_by }}.
use strict;
use warnings;
{{ $perl_prereq ? qq[use $perl_prereq;] : ''; }}
use ExtUtils::MakeMaker{{ defined $eumm_version && 0+$eumm_version ? ' ' . $eumm_version : '' }};
{{ $share_dir_code{preamble} || '' }}
my {{ $WriteMakefileArgs }}
my {{ $fallback_prereqs }}
unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) {
delete $WriteMakefileArgs{TEST_REQUIRES};
delete $WriteMakefileArgs{BUILD_REQUIRES};
$WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs;
}
delete $WriteMakefileArgs{CONFIGURE_REQUIRES}
unless eval { ExtUtils::MakeMaker->VERSION(6.52) };
WriteMakefile(%WriteMakefileArgs);
{{ $share_dir_code{postamble} || '' }}!;
sub register_prereqs {
my ($self) = @_;
$self->zilla->register_prereqs(
{ phase => 'configure' },
'ExtUtils::MakeMaker' => $self->eumm_version || 0,
);
return unless keys %{ $self->zilla->_share_dir_map };
$self->zilla->register_prereqs(
{ phase => 'configure' },
'File::ShareDir::Install' => 0.06,
);
}
sub gather_files {
my ($self) = @_;
require Dist::Zilla::File::InMemory;
my $file = Dist::Zilla::File::InMemory->new({
name => 'Makefile.PL',
content => $template, # template evaluated later
});
$self->add_file($file);
return;
}
sub share_dir_code {
my ($self) = @_;
my $share_dir_code = {};
my $share_dir_map = $self->zilla->_share_dir_map;
if ( keys %$share_dir_map ) {
my $preamble = <<'PREAMBLE';
use File::ShareDir::Install;
$File::ShareDir::Install::INCLUDE_DOTFILES = 1;
$File::ShareDir::Install::INCLUDE_DOTDIRS = 1;
PREAMBLE
if ( my $dist_share_dir = $share_dir_map->{dist} ) {
$dist_share_dir = quotemeta $dist_share_dir;
$preamble .= qq{install_share dist => "$dist_share_dir";\n};
}
if ( my $mod_map = $share_dir_map->{module} ) {
for my $mod ( keys %$mod_map ) {
my $mod_share_dir = quotemeta $mod_map->{$mod};
$preamble .= qq{install_share module => "$mod", "$mod_share_dir";\n};
}
}
$share_dir_code->{preamble} = "\n" . $preamble . "\n";
$share_dir_code->{postamble}
= qq{\n\{\npackage\nMY;\nuse File::ShareDir::Install qw(postamble);\n\}\n};
}
return $share_dir_code;
}
sub write_makefile_args {
my ($self) = @_;
- my $name = $self->zilla->name =~ s/-/::/gr;
+ my $name = $self->main_module || ($self->zilla->name =~ s/-/::/gr);
my @exe_files = map { $_->name }
@{ $self->zilla->find_files(':ExecFiles') };
$self->log_fatal("can't install files with whitespace in their names")
if grep { /\s/ } @exe_files;
my %test_dirs;
for my $file (@{ $self->zilla->files }) {
next unless $file->name =~ m{\At/.+\.t\z};
my $dir = $file->name =~ s{/[^/]+\.t\z}{/*.t}gr;
$test_dirs{ $dir } = 1;
}
my $prereqs = $self->zilla->prereqs;
my $perl_prereq = $prereqs->requirements_for(qw(runtime requires))
->clone
->add_requirements($prereqs->requirements_for(qw(configure requires)))
->add_requirements($prereqs->requirements_for(qw(build requires)))
->add_requirements($prereqs->requirements_for(qw(test requires)))
->as_string_hash->{perl};
$perl_prereq = version->parse($perl_prereq)->numify if $perl_prereq;
my $prereqs_dump = sub {
$self->_normalize_eumm_versions(
$prereqs->requirements_for(@_)
->clone
->clear_requirement('perl')
->as_string_hash
);
};
my %require_prereqs = map {
$_ => $prereqs_dump->($_, 'requires');
} qw(configure build test runtime);
# EUMM may soon be able to support this, but until we decide to inject a
# higher configure-requires version, we should at least warn the user
# https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
foreach my $phase (qw(configure build test runtime)) {
if (my @version_ranges = pairgrep { defined($b) && !version::is_lax($b) } %{ $require_prereqs{$phase} }
and ($self->eumm_version || 0) < '7.1101') {
$self->log_fatal([
'found version range in %s prerequisites, which ExtUtils::MakeMaker cannot parse (must specify eumm_version of at least 7.1101): %s %s',
$phase, $_->[0], $_->[1]
]) foreach pairs @version_ranges;
}
}
my %write_makefile_args = (
DISTNAME => $self->zilla->name,
NAME => $name,
AUTHOR => join(q{, }, @{ $self->zilla->authors }),
ABSTRACT => $self->zilla->abstract,
VERSION => $self->zilla->version,
LICENSE => $self->zilla->license->meta_yml_name,
@exe_files ? ( EXE_FILES => [ sort @exe_files ] ) : (),
CONFIGURE_REQUIRES => $require_prereqs{configure},
keys %{ $require_prereqs{build} } ? ( BUILD_REQUIRES => $require_prereqs{build} ) : (),
keys %{ $require_prereqs{test} } ? ( TEST_REQUIRES => $require_prereqs{test} ) : (),
PREREQ_PM => $require_prereqs{runtime},
test => { TESTS => join q{ }, sort keys %test_dirs },
);
$write_makefile_args{MIN_PERL_VERSION} = $perl_prereq if $perl_prereq;
return \%write_makefile_args;
}
sub _normalize_eumm_versions {
my ($self, $prereqs) = @_;
for my $v (values %$prereqs) {
if (version::is_strict($v)) {
my $version = version->parse($v);
if ($version->is_qv) {
if ((() = $v =~ /\./g) > 1) {
$v =~ s/^v//;
}
else {
$v = $version->numify;
}
}
}
}
return $prereqs;
}
sub _dump_as {
my ($self, $ref, $name) = @_;
require Data::Dumper;
my $dumper = Data::Dumper->new( [ $ref ], [ $name ] );
$dumper->Sortkeys( 1 );
$dumper->Indent( 1 );
$dumper->Useqq( 1 );
return $dumper->Dump;
}
sub fallback_prereq_pm {
my $self = shift;
my $fallback
= $self->_normalize_eumm_versions(
$self->zilla->prereqs->merged_requires
->clone
->clear_requirement('perl')
->as_string_hash
);
return $self->_dump_as( $fallback, '*FallbackPrereqs' );
}
sub setup_installer {
my ($self) = @_;
my $write_makefile_args = $self->write_makefile_args;
$self->__write_makefile_args($write_makefile_args); # save for testing
my $perl_prereq = $write_makefile_args->{MIN_PERL_VERSION};
my $dumped_args = $self->_dump_as($write_makefile_args, '*WriteMakefileArgs');
my $file = first { $_->name eq 'Makefile.PL' } @{$self->zilla->files};
$self->log_debug([ 'updating contents of Makefile.PL in memory' ]);
my $attribution = $self->static_attribution
? ref($self)
: sprintf("%s v%s", ref($self), $self->VERSION || '(dev)');
my $content = $self->fill_in_string(
$file->content,
{
eumm_version => \($self->eumm_version),
perl_prereq => \$perl_prereq,
share_dir_code => $self->share_dir_code,
fallback_prereqs => \($self->fallback_prereq_pm),
WriteMakefileArgs => \$dumped_args,
generated_by => \$attribution,
},
);
$file->content($content);
return;
}
# XXX: Just here to facilitate testing. -- rjbs, 2010-03-20
has __write_makefile_args => (
is => 'rw',
isa => 'HashRef',
);
__PACKAGE__->meta->make_immutable;
1;
=head1 SEE ALSO
Core Dist::Zilla plugins:
L<@Basic|Dist::Zilla::PluginBundle::Basic>,
L<ModuleBuild|Dist::Zilla::Plugin::ModuleBuild>,
L<Manifest|Dist::Zilla::Plugin::Manifest>.
Dist::Zilla roles:
L<BuildRunner|Dist::Zilla::Role::FileGatherer>,
L<InstallTool|Dist::Zilla::Role::InstallTool>,
L<PrereqSource|Dist::Zilla::Role::PrereqSource>,
L<TestRunner|Dist::Zilla::Role::TestRunner>.
=cut
diff --git a/t/plugins/makemaker.t b/t/plugins/makemaker.t
index 0439098..798b2c5 100644
--- a/t/plugins/makemaker.t
+++ b/t/plugins/makemaker.t
@@ -1,154 +1,193 @@
use strict;
use warnings;
use Test::More 0.88;
use Test::Deep;
use Test::Fatal;
use Test::DZil;
{
my $tzil = Builder->from_config(
{ dist_root => 'corpus/dist/DZT' },
{
add_files => {
'source/dist.ini' => simple_ini(
'GatherDir',
'MakeMaker',
[ Prereqs => { 'Foo::Bar' => '1.20',
perl => '5.008',
Baz => '1.2.3',
Buzz => 'v1.2' } ],
[ Prereqs => BuildRequires => { 'Builder::Bob' => '9.901' } ],
[ Prereqs => TestRequires => { 'Test::Deet' => '7',
perl => '5.008' } ],
[ Prereqs => ConfigureRequires => { perl => '5.010' } ],
),
},
},
);
$tzil->build;
my $makemaker = $tzil->plugin_named('MakeMaker');
my %want = (
DISTNAME => 'DZT-Sample',
NAME => 'DZT::Sample',
ABSTRACT => 'Sample DZ Dist',
VERSION => '0.001',
AUTHOR => 'E. Xavier Ample <[email protected]>',
LICENSE => 'perl',
MIN_PERL_VERSION => '5.010',
test => { TESTS => 't/*.t' },
PREREQ_PM => {
'Foo::Bar' => '1.20',
'Baz' => '1.2.3',
'Buzz' => '1.2.0',
},
BUILD_REQUIRES => {
'Builder::Bob' => '9.901',
},
TEST_REQUIRES => {
'Test::Deet' => '7',
},
CONFIGURE_REQUIRES => {
'ExtUtils::MakeMaker' => '0'
},
test => { TESTS => 't/*.t' },
);
cmp_deeply(
$makemaker->__write_makefile_args,
\%want,
'correct makemaker args generated',
);
}
+{
+ my $tzil = Builder->from_config(
+ { dist_root => 'corpus/dist/DZT' },
+ {
+ add_files => {
+ 'source/dist.ini' => simple_ini(
+ 'GatherDir',
+ [ 'MakeMaker', { main_module => "DZT::Main" } ],
+ ),
+ },
+ },
+ );
+
+ $tzil->build;
+
+ my $makemaker = $tzil->plugin_named('MakeMaker');
+
+ my %want = (
+ DISTNAME => 'DZT-Sample',
+ NAME => 'DZT::Main',
+ ABSTRACT => 'Sample DZ Dist',
+ VERSION => '0.001',
+ AUTHOR => 'E. Xavier Ample <[email protected]>',
+ LICENSE => 'perl',
+ test => { TESTS => 't/*.t' },
+ PREREQ_PM => { },
+ CONFIGURE_REQUIRES => {
+ 'ExtUtils::MakeMaker' => '0'
+ },
+ test => { TESTS => 't/*.t' },
+ );
+
+ cmp_deeply(
+ $makemaker->__write_makefile_args,
+ \%want,
+ 'correct makemaker args generated',
+ );
+}
+
{
my $tzil = Builder->from_config(
{ dist_root => 'corpus/dist/DZT' },
{
add_files => {
'source/dist.ini' => simple_ini(
'GatherDir',
'MakeMaker',
[ Prereqs => { perl => '5.8.1' } ],
[ Prereqs => BuildRequires => { 'Builder::Bob' => 0 } ],
[ Prereqs => TestRequires => { 'Tester::Bob' => 0 } ],
[ Prereqs => RuntimeRequires => { 'Runner::Bob' => 0 } ],
),
},
},
);
$tzil->build;
my $content = $tzil->slurp_file('build/Makefile.PL');
like($content, qr/^use 5\.008001;\s*$/m, "normalized the perl version needed");
$content =~ m'^my %FallbackPrereqs = \(\n([^;]+)^\);$'mg;
like($1, qr'"Builder::Bob" => ', 'build-requires prereqs made it into %FallbackPrereqs');
like($1, qr'"Tester::Bob" => ', 'test-requires prereqs made it into %FallbackPrereqs');
like($1, qr'"Runner::Bob" => ', 'runtime-requires prereqs made it into %FallbackPrereqs');
}
{
my $tzil = Builder->from_config(
{ dist_root => 'does-not-exist' },
{
add_files => {
'source/dist.ini' => simple_ini(
'GatherDir',
'MakeMaker',
[ Prereqs => { 'External::Module' => '<= 1.23' } ],
),
'source/lib/Foo.pm' => "package Foo;\n1\n",
},
},
);
like(
exception { $tzil->build },
qr/\Q[MakeMaker] found version range in runtime prerequisites, which ExtUtils::MakeMaker cannot parse (must specify eumm_version of at least 7.1101): External::Module <= 1.23\E/,
'build does not permit passing unparsable version range',
);
diag 'got log messages: ', explain $tzil->log_messages
if not Test::Builder->new->is_passing;
}
{
my $tzil = Builder->from_config(
{ dist_root => 'does-not-exist' },
{
add_files => {
'source/dist.ini' => simple_ini(
'GatherDir',
[ 'MakeMaker' => { eumm_version => '7.12' } ],
[ Prereqs => { 'External::Module' => '<= 1.23' } ],
),
'source/lib/Foo.pm' => "package Foo;\n1\n",
},
},
);
$tzil->chrome->logger->set_debug(1);
is(
exception { $tzil->build },
undef,
'build proceeds normally',
);
ok(
!(grep { m'[MakeMaker] found version range' } @{ $tzil->log_messages }),
'got no warning about probably-unparsable version range',
);
diag 'got log messages: ', explain $tzil->log_messages
if not Test::Builder->new->is_passing;
}
done_testing;
|
rjbs/Dist-Zilla
|
64ae7d8a62022ea8e6bdf7e84e3bd9e9c54808df
|
Fix build in Windows/msys2 trying to remove a directory fails
|
diff --git a/lib/Dist/Zilla/Dist/Builder.pm b/lib/Dist/Zilla/Dist/Builder.pm
index d82f07e..15078bc 100644
--- a/lib/Dist/Zilla/Dist/Builder.pm
+++ b/lib/Dist/Zilla/Dist/Builder.pm
@@ -233,652 +233,654 @@ sub _build_share_dir_map {
my $share_dir_map = {};
for my $plugin (@{ $self->plugins_with(-ShareDir) }) {
next unless my $sub_map = $plugin->share_dir_map;
if ( $sub_map->{dist} ) {
$self->log_fatal("can't install more than one distribution ShareDir")
if $share_dir_map->{dist};
$share_dir_map->{dist} = $sub_map->{dist};
}
if ( my $mod_map = $sub_map->{module} ) {
for my $mod ( keys %$mod_map ) {
$self->log_fatal("can't install more than one ShareDir for $mod")
if $share_dir_map->{module}{$mod};
$share_dir_map->{module}{$mod} = $mod_map->{$mod};
}
}
}
return $share_dir_map;
}
sub _load_config {
my ($class, $arg) = @_;
$arg ||= {};
my $config_class =
$arg->{config_class} ||= 'Dist::Zilla::MVP::Reader::Finder';
require_module($config_class);
$arg->{chrome}->logger->log_debug(
{ prefix => '[DZ] ' },
"reading configuration using $config_class"
);
my $root = $arg->{root};
require Dist::Zilla::MVP::Assembler::Zilla;
require Dist::Zilla::MVP::Section;
my $assembler = Dist::Zilla::MVP::Assembler::Zilla->new({
chrome => $arg->{chrome},
zilla_class => $class,
section_class => 'Dist::Zilla::MVP::Section', # make this DZMA default
});
for ($assembler->sequence->section_named('_')) {
$_->add_value(chrome => $arg->{chrome});
$_->add_value(root => $arg->{root});
$_->add_value(_global_stashes => $arg->{_global_stashes})
if $arg->{_global_stashes};
}
my $seq;
try {
$seq = $config_class->read_config(
$root->child('dist'),
{
assembler => $assembler
},
);
} catch {
die $_ unless try {
$_->isa('Config::MVP::Error')
and $_->ident eq 'package not installed'
};
my $package = $_->package;
my $bundle = $_->section_name =~ m{^@(?!.*/)} ? ' bundle' : '';
die <<"END_DIE";
Required plugin$bundle $package isn't installed.
Run 'dzil authordeps' to see a list of all required plugins.
You can pipe the list to your CPAN client to install or update them:
dzil authordeps --missing | cpanm
END_DIE
};
return $seq;
}
=method build_in
$zilla->build_in($root);
This method builds the distribution in the given directory. If no directory
name is given, it defaults to DistName-Version. If the distribution has
already been built, an exception will be thrown.
=method build
This method just calls C<build_in> with no arguments. It gets you the default
behavior without the weird-looking formulation of C<build_in> with no object
for the preposition!
=cut
sub build { $_[0]->build_in }
sub build_in {
my ($self, $root) = @_;
$self->log_fatal("tried to build with a minter")
if $self->isa('Dist::Zilla::Dist::Minter');
$self->log_fatal("attempted to build " . $self->name . " a second time")
if $self->built_in;
$_->before_build for @{ $self->plugins_with(-BeforeBuild) };
$self->log("beginning to build " . $self->name);
$_->gather_files for @{ $self->plugins_with(-FileGatherer) };
$_->set_file_encodings for @{ $self->plugins_with(-EncodingProvider) };
$_->prune_files for @{ $self->plugins_with(-FilePruner) };
$self->version; # instantiate this lazy attribute now that files are gathered
$_->munge_files for @{ $self->plugins_with(-FileMunger) };
$_->register_prereqs for @{ $self->plugins_with(-PrereqSource) };
$self->prereqs->finalize;
# Barf if someone has already set up a prereqs entry? -- rjbs, 2010-04-13
$self->distmeta->{prereqs} = $self->prereqs->as_string_hash;
$_->setup_installer for @{ $self->plugins_with(-InstallTool) };
$self->_check_dupe_files;
my $build_root = $self->_prep_build_root($root);
$self->log("writing " . $self->name . " in $build_root");
for my $file (@{ $self->files }) {
$self->_write_out_file($file, $build_root);
}
$_->after_build({ build_root => $build_root })
for @{ $self->plugins_with(-AfterBuild) };
$self->built_in($build_root);
}
=attr built_in
This is the L<Path::Tiny>, if any, in which the dist has been built.
=cut
has built_in => (
is => 'rw',
isa => Path,
init_arg => undef,
coerce => 1,
);
=method ensure_built_in
$zilla->ensure_built_in($root);
This method behaves like C<L</build_in>>, but if the dist is already built in
C<$root> (or the default root, if no root is given), no exception is raised.
=method ensure_built
This method just calls C<ensure_built_in> with no arguments. It gets you the
default behavior without the weird-looking formulation of C<ensure_built_in>
with no object for the preposition!
=cut
sub ensure_built {
$_[0]->ensure_built_in;
}
sub ensure_built_in {
my ($self, $root) = @_;
# $root ||= $self->name . q{-} . $self->version;
return $self->built_in if $self->built_in and
(!$root or ($self->built_in eq $root));
Carp::croak("dist is already built, but not in $root") if $self->built_in;
$self->build_in($root);
}
=method dist_basename
my $basename = $zilla->dist_basename;
This method will return the dist's basename (e.g. C<Dist-Name-1.01>.
The basename is used as the top-level directory in the tarball. It
does not include C<-TRIAL>, even if building a trial dist.
=cut
sub dist_basename {
my ($self) = @_;
return join(q{},
$self->name,
'-',
$self->version,
);
}
=method archive_basename
my $basename = $zilla->archive_basename;
This method will return the filename, without the format extension
(e.g. C<Dist-Name-1.01> or C<Dist-Name-1.01-TRIAL>).
=cut
sub archive_basename {
my ($self) = @_;
return join q{},
$self->dist_basename,
( $self->is_trial && $self->version !~ /_/ ? '-TRIAL' : '' ),
;
}
=method archive_filename
my $tarball = $zilla->archive_filename;
This method will return the filename (e.g. C<Dist-Name-1.01.tar.gz>)
of the tarball of this distribution. It will include C<-TRIAL> if building a
trial distribution, unless the version contains an underscore. The tarball
might not exist.
=cut
sub archive_filename {
my ($self) = @_;
return join q{}, $self->archive_basename, '.tar.gz';
}
=method build_archive
$zilla->build_archive;
This method will ensure that the dist has been built, and will then build a
tarball of the build directory in the current directory.
=cut
sub build_archive {
my ($self) = @_;
my $built_in = $self->ensure_built;
my $basedir = path($self->dist_basename);
$_->before_archive for $self->plugins_with(-BeforeArchive)->@*;
for my $builder ($self->plugins_with(-ArchiveBuilder)->@*) {
my $file = $builder->build_archive($self->archive_basename, $built_in, $basedir);
return $file if defined $file;
}
my $method = eval { +require Archive::Tar::Wrapper;
Archive::Tar::Wrapper->VERSION('0.15'); 1 }
? '_build_archive_with_wrapper'
: '_build_archive';
my $archive = $self->$method($built_in, $basedir);
my $file = path($self->archive_filename);
$self->log("writing archive to $file");
$archive->write("$file", 9);
return $file;
}
sub _build_archive {
my ($self, $built_in, $basedir) = @_;
$self->log("building archive with Archive::Tar; install Archive::Tar::Wrapper 0.15 or newer for improved speed");
require Archive::Tar;
my $archive = Archive::Tar->new;
my %seen_dir;
for my $distfile (
sort { length($a->name) <=> length($b->name) } @{ $self->files }
) {
my $in = path($distfile->name)->parent;
unless ($seen_dir{ $in }++) {
$archive->add_data(
$basedir->child($in),
'',
{ type => Archive::Tar::Constant::DIR(), mode => 0755 },
)
}
my $filename = $built_in->child( $distfile->name );
$archive->add_data(
$basedir->child( $distfile->name ),
path($filename)->slurp_raw,
{ mode => (stat $filename)[2] & ~022 },
);
}
return $archive;
}
sub _build_archive_with_wrapper {
my ($self, $built_in, $basedir) = @_;
$self->log("building archive with Archive::Tar::Wrapper");
my $archive = Archive::Tar::Wrapper->new;
for my $distfile (
sort { length($a->name) <=> length($b->name) } @{ $self->files }
) {
my $in = path($distfile->name)->parent;
my $filename = $built_in->child( $distfile->name );
$archive->add(
$basedir->child( $distfile->name )->stringify,
$filename->stringify,
{ perm => (stat $filename)[2] & ~022 },
);
}
return $archive;
}
sub _prep_build_root {
my ($self, $build_root) = @_;
$build_root = path($build_root || $self->dist_basename);
$build_root->mkpath unless -d $build_root;
my $dist_root = $self->root;
return $build_root if !-d $build_root;
my $ok = eval { $build_root->remove_tree({ safe => 0 }); 1 };
die "unable to delete '$build_root' in preparation of build: $@" unless $ok;
# the following is done only on windows, and only if the deletion failed,
# yet rmtree reported success, because currently rmdir is non-blocking as per:
# https://rt.perl.org/Ticket/Display.html?id=123958
if ( $^O eq 'MSWin32' and -d $build_root ) {
$self->log("spinning for at least one second to allow other processes to release locks on $build_root");
my $timeout = time + 2;
while(time != $timeout and -d $build_root) { }
die "unable to delete '$build_root' in preparation of build because some process has a lock on it"
if -d $build_root;
}
return $build_root;
}
=method release
$zilla->release;
This method releases the distribution, probably by uploading it to the CPAN.
The actual effects of this method (as with most of the methods) is determined
by the loaded plugins.
=cut
sub release {
my $self = shift;
Carp::croak("you can't release without any Releaser plugins")
unless my @releasers = @{ $self->plugins_with(-Releaser) };
$ENV{DZIL_RELEASING} = 1;
my $tgz = $self->build_archive;
# call all plugins implementing BeforeRelease role
$_->before_release($tgz) for @{ $self->plugins_with(-BeforeRelease) };
# do the actual release
$_->release($tgz) for @releasers;
# call all plugins implementing AfterRelease role
$_->after_release($tgz) for @{ $self->plugins_with(-AfterRelease) };
}
=method clean
This method removes temporary files and directories suspected to have been
produced by the Dist::Zilla build process. Specifically, it deletes the
F<.build> directory and any entity that starts with the dist name and a hyphen,
like matching the glob C<Your-Dist-*>.
=cut
sub clean {
my ($self, $dry_run) = @_;
require File::Path;
for my $x (grep { -e } '.build', glob($self->name . '-*')) {
if ($dry_run) {
$self->log("clean: would remove $x");
} else {
$self->log("clean: removing $x");
File::Path::rmtree($x);
}
};
}
=method ensure_built_in_tmpdir
$zilla->ensure_built_in_tmpdir;
This method will consistently build the distribution in a temporary
subdirectory. It will return the path for the temporary build location.
=cut
sub ensure_built_in_tmpdir {
my $self = shift;
require File::Temp;
my $build_root = path('.build');
$build_root->mkpath unless -d $build_root;
my $target = path( File::Temp::tempdir(DIR => $build_root) );
$self->log("building distribution under $target for installation");
my $os_has_symlinks = eval { symlink("",""); 1 };
my $previous;
my $latest;
if( $os_has_symlinks ) {
$previous = path( $build_root, 'previous' );
$latest = path( $build_root, 'latest' );
if( -l $previous ) {
$previous->remove
or $self->log("cannot remove old .build/previous link");
}
if( -l $latest ) {
rename $latest, $previous
or $self->log("cannot move .build/latest link to .build/previous");
}
symlink $target->basename, $latest
or $self->log('cannot create link .build/latest');
}
$self->ensure_built_in($target);
return ($target, $latest, $previous);
}
=method install
$zilla->install( \%arg );
This method installs the distribution locally. The distribution will be built
in a temporary subdirectory, then the process will change directory to that
subdir and an installer will be run.
Valid arguments are:
keep_build_dir - if true, don't rmtree the build dir, even if everything
seemed to work
install_command - the command to run in the subdir to install the dist
default (roughly): $^X -MCPAN -einstall .
this argument should be an arrayref
=cut
sub install {
my ($self, $arg) = @_;
$arg ||= {};
my ($target, $latest) = $self->ensure_built_in_tmpdir;
my $ok = eval {
## no critic Punctuation
my $wd = File::pushd::pushd($target);
my @cmd = $arg->{install_command}
? @{ $arg->{install_command} }
: (cpanm => ".");
$self->log_debug([ 'installing via %s', \@cmd ]);
system(@cmd) && $self->log_fatal([ "error running %s", \@cmd ]);
1;
};
unless ($ok) {
my $error = $@ || '(exception clobered)';
$self->log("install failed, left failed dist in place at $target");
die $error;
}
if ($arg->{keep_build_dir}) {
$self->log("all's well; left dist in place at $target");
} else {
$self->log("all's well; removing $target");
$target->remove_tree({ safe => 0 });
+ $latest->remove_tree({ safe => 0 }) if -d $latest; # error cannot unlink, is a directory
$latest->remove if $latest;
}
return;
}
=method test
$zilla->test(\%arg);
This method builds a new copy of the distribution and tests it using
C<L</run_tests_in>>.
C<\%arg> may be omitted. Otherwise, valid arguments are:
keep_build_dir - if true, don't rmtree the build dir, even if everything
seemed to work
=cut
sub test {
my ($self, $arg) = @_;
Carp::croak("you can't test without any TestRunner plugins")
unless my @testers = @{ $self->plugins_with(-TestRunner) };
my ($target, $latest) = $self->ensure_built_in_tmpdir;
my $error = $self->run_tests_in($target, $arg);
if ($arg and $arg->{keep_build_dir}) {
$self->log("all's well; left dist in place at $target");
return;
}
$self->log("all's well; removing $target");
$target->remove_tree({ safe => 0 });
$latest->remove_tree({ safe => 0 }) if -d $latest; # error cannot unlink, is a directory
$latest->remove if $latest;
}
=method run_tests_in
my $error = $zilla->run_tests_in($directory, $arg);
This method runs the tests in $directory (a Path::Tiny), which must contain an
already-built copy of the distribution. It will throw an exception if there
are test failures.
It does I<not> set any of the C<*_TESTING> environment variables, nor
does it clean up C<$directory> afterwards.
=cut
sub run_tests_in {
my ($self, $target, $arg) = @_;
Carp::croak("you can't test without any TestRunner plugins")
unless my @testers = @{ $self->plugins_with(-TestRunner) };
for my $tester (@testers) {
my $wd = File::pushd::pushd($target);
$tester->test( $target, $arg );
}
}
=method run_in_build
$zilla->run_in_build( \@cmd );
This method makes a temporary directory, builds the distribution there,
executes all the dist's L<BuildRunner|Dist::Zilla::Role::BuildRunner>s
(unless directed not to, via C<< $arg->{build} = 0 >>), and
then runs the given command in the build directory. If the command exits
non-zero, the directory will be left in place.
=cut
sub run_in_build {
my ($self, $cmd, $arg) = @_;
$self->log_fatal("you can't build without any BuildRunner plugins")
unless ($arg and exists $arg->{build} and ! $arg->{build})
or @{ $self->plugins_with(-BuildRunner) };
require "Config.pm"; # skip autoprereq
my ($target, $latest) = $self->ensure_built_in_tmpdir;
my $abstarget = $target->absolute;
# building the dist for real
my $ok = eval {
my $wd = File::pushd::pushd($target);
if ($arg and exists $arg->{build} and ! $arg->{build}) {
system(@$cmd) and die "error while running: @$cmd";
return 1;
}
$self->_ensure_blib;
local $ENV{PERL5LIB} = join $Config::Config{path_sep},
(map { $abstarget->child('blib', $_) } qw(arch lib)),
(defined $ENV{PERL5LIB} ? $ENV{PERL5LIB} : ());
local $ENV{PATH} = join $Config::Config{path_sep},
(map { $abstarget->child('blib', $_) } qw(bin script)),
(defined $ENV{PATH} ? $ENV{PATH} : ());
system(@$cmd) and die "error while running: @$cmd";
1;
};
if ($ok) {
$self->log("all's well; removing $target");
$target->remove_tree({ safe => 0 });
+ $latest->remove_tree({ safe => 0 }) if -d $latest; # error cannot unlink, is a directory
$latest->remove if $latest;
} else {
my $error = $@ || '(unknown error)';
$self->log($error);
$self->log_fatal("left failed dist in place at $target");
}
}
# Ensures that a F<blib> directory exists in the build, by invoking all
# C<-BuildRunner> plugins to generate it. Useful for commands that operate on
# F<blib>, such as C<test> or C<run>.
sub _ensure_blib {
my ($self) = @_;
unless ( -d 'blib' ) {
my @builders = @{ $self->plugins_with( -BuildRunner ) };
$self->log_fatal("no BuildRunner plugins specified") unless @builders;
$_->build for @builders;
$self->log_fatal("no blib; failed to build properly?") unless -d 'blib';
}
}
__PACKAGE__->meta->make_immutable;
1;
|
rjbs/Dist-Zilla
|
3d7984d2ead0465205c3af665b50487c33423323
|
Fix build in Windows/msys2 symlink tests must be skipped trying to remove a directory fails
|
diff --git a/lib/Dist/Zilla/Dist/Builder.pm b/lib/Dist/Zilla/Dist/Builder.pm
index b1fc4e8..d82f07e 100644
--- a/lib/Dist/Zilla/Dist/Builder.pm
+++ b/lib/Dist/Zilla/Dist/Builder.pm
@@ -269,615 +269,616 @@ sub _load_config {
);
my $root = $arg->{root};
require Dist::Zilla::MVP::Assembler::Zilla;
require Dist::Zilla::MVP::Section;
my $assembler = Dist::Zilla::MVP::Assembler::Zilla->new({
chrome => $arg->{chrome},
zilla_class => $class,
section_class => 'Dist::Zilla::MVP::Section', # make this DZMA default
});
for ($assembler->sequence->section_named('_')) {
$_->add_value(chrome => $arg->{chrome});
$_->add_value(root => $arg->{root});
$_->add_value(_global_stashes => $arg->{_global_stashes})
if $arg->{_global_stashes};
}
my $seq;
try {
$seq = $config_class->read_config(
$root->child('dist'),
{
assembler => $assembler
},
);
} catch {
die $_ unless try {
$_->isa('Config::MVP::Error')
and $_->ident eq 'package not installed'
};
my $package = $_->package;
my $bundle = $_->section_name =~ m{^@(?!.*/)} ? ' bundle' : '';
die <<"END_DIE";
Required plugin$bundle $package isn't installed.
Run 'dzil authordeps' to see a list of all required plugins.
You can pipe the list to your CPAN client to install or update them:
dzil authordeps --missing | cpanm
END_DIE
};
return $seq;
}
=method build_in
$zilla->build_in($root);
This method builds the distribution in the given directory. If no directory
name is given, it defaults to DistName-Version. If the distribution has
already been built, an exception will be thrown.
=method build
This method just calls C<build_in> with no arguments. It gets you the default
behavior without the weird-looking formulation of C<build_in> with no object
for the preposition!
=cut
sub build { $_[0]->build_in }
sub build_in {
my ($self, $root) = @_;
$self->log_fatal("tried to build with a minter")
if $self->isa('Dist::Zilla::Dist::Minter');
$self->log_fatal("attempted to build " . $self->name . " a second time")
if $self->built_in;
$_->before_build for @{ $self->plugins_with(-BeforeBuild) };
$self->log("beginning to build " . $self->name);
$_->gather_files for @{ $self->plugins_with(-FileGatherer) };
$_->set_file_encodings for @{ $self->plugins_with(-EncodingProvider) };
$_->prune_files for @{ $self->plugins_with(-FilePruner) };
$self->version; # instantiate this lazy attribute now that files are gathered
$_->munge_files for @{ $self->plugins_with(-FileMunger) };
$_->register_prereqs for @{ $self->plugins_with(-PrereqSource) };
$self->prereqs->finalize;
# Barf if someone has already set up a prereqs entry? -- rjbs, 2010-04-13
$self->distmeta->{prereqs} = $self->prereqs->as_string_hash;
$_->setup_installer for @{ $self->plugins_with(-InstallTool) };
$self->_check_dupe_files;
my $build_root = $self->_prep_build_root($root);
$self->log("writing " . $self->name . " in $build_root");
for my $file (@{ $self->files }) {
$self->_write_out_file($file, $build_root);
}
$_->after_build({ build_root => $build_root })
for @{ $self->plugins_with(-AfterBuild) };
$self->built_in($build_root);
}
=attr built_in
This is the L<Path::Tiny>, if any, in which the dist has been built.
=cut
has built_in => (
is => 'rw',
isa => Path,
init_arg => undef,
coerce => 1,
);
=method ensure_built_in
$zilla->ensure_built_in($root);
This method behaves like C<L</build_in>>, but if the dist is already built in
C<$root> (or the default root, if no root is given), no exception is raised.
=method ensure_built
This method just calls C<ensure_built_in> with no arguments. It gets you the
default behavior without the weird-looking formulation of C<ensure_built_in>
with no object for the preposition!
=cut
sub ensure_built {
$_[0]->ensure_built_in;
}
sub ensure_built_in {
my ($self, $root) = @_;
# $root ||= $self->name . q{-} . $self->version;
return $self->built_in if $self->built_in and
(!$root or ($self->built_in eq $root));
Carp::croak("dist is already built, but not in $root") if $self->built_in;
$self->build_in($root);
}
=method dist_basename
my $basename = $zilla->dist_basename;
This method will return the dist's basename (e.g. C<Dist-Name-1.01>.
The basename is used as the top-level directory in the tarball. It
does not include C<-TRIAL>, even if building a trial dist.
=cut
sub dist_basename {
my ($self) = @_;
return join(q{},
$self->name,
'-',
$self->version,
);
}
=method archive_basename
my $basename = $zilla->archive_basename;
This method will return the filename, without the format extension
(e.g. C<Dist-Name-1.01> or C<Dist-Name-1.01-TRIAL>).
=cut
sub archive_basename {
my ($self) = @_;
return join q{},
$self->dist_basename,
( $self->is_trial && $self->version !~ /_/ ? '-TRIAL' : '' ),
;
}
=method archive_filename
my $tarball = $zilla->archive_filename;
This method will return the filename (e.g. C<Dist-Name-1.01.tar.gz>)
of the tarball of this distribution. It will include C<-TRIAL> if building a
trial distribution, unless the version contains an underscore. The tarball
might not exist.
=cut
sub archive_filename {
my ($self) = @_;
return join q{}, $self->archive_basename, '.tar.gz';
}
=method build_archive
$zilla->build_archive;
This method will ensure that the dist has been built, and will then build a
tarball of the build directory in the current directory.
=cut
sub build_archive {
my ($self) = @_;
my $built_in = $self->ensure_built;
my $basedir = path($self->dist_basename);
$_->before_archive for $self->plugins_with(-BeforeArchive)->@*;
for my $builder ($self->plugins_with(-ArchiveBuilder)->@*) {
my $file = $builder->build_archive($self->archive_basename, $built_in, $basedir);
return $file if defined $file;
}
my $method = eval { +require Archive::Tar::Wrapper;
Archive::Tar::Wrapper->VERSION('0.15'); 1 }
? '_build_archive_with_wrapper'
: '_build_archive';
my $archive = $self->$method($built_in, $basedir);
my $file = path($self->archive_filename);
$self->log("writing archive to $file");
$archive->write("$file", 9);
return $file;
}
sub _build_archive {
my ($self, $built_in, $basedir) = @_;
$self->log("building archive with Archive::Tar; install Archive::Tar::Wrapper 0.15 or newer for improved speed");
require Archive::Tar;
my $archive = Archive::Tar->new;
my %seen_dir;
for my $distfile (
sort { length($a->name) <=> length($b->name) } @{ $self->files }
) {
my $in = path($distfile->name)->parent;
unless ($seen_dir{ $in }++) {
$archive->add_data(
$basedir->child($in),
'',
{ type => Archive::Tar::Constant::DIR(), mode => 0755 },
)
}
my $filename = $built_in->child( $distfile->name );
$archive->add_data(
$basedir->child( $distfile->name ),
path($filename)->slurp_raw,
{ mode => (stat $filename)[2] & ~022 },
);
}
return $archive;
}
sub _build_archive_with_wrapper {
my ($self, $built_in, $basedir) = @_;
$self->log("building archive with Archive::Tar::Wrapper");
my $archive = Archive::Tar::Wrapper->new;
for my $distfile (
sort { length($a->name) <=> length($b->name) } @{ $self->files }
) {
my $in = path($distfile->name)->parent;
my $filename = $built_in->child( $distfile->name );
$archive->add(
$basedir->child( $distfile->name )->stringify,
$filename->stringify,
{ perm => (stat $filename)[2] & ~022 },
);
}
return $archive;
}
sub _prep_build_root {
my ($self, $build_root) = @_;
$build_root = path($build_root || $self->dist_basename);
$build_root->mkpath unless -d $build_root;
my $dist_root = $self->root;
return $build_root if !-d $build_root;
my $ok = eval { $build_root->remove_tree({ safe => 0 }); 1 };
die "unable to delete '$build_root' in preparation of build: $@" unless $ok;
# the following is done only on windows, and only if the deletion failed,
# yet rmtree reported success, because currently rmdir is non-blocking as per:
# https://rt.perl.org/Ticket/Display.html?id=123958
if ( $^O eq 'MSWin32' and -d $build_root ) {
$self->log("spinning for at least one second to allow other processes to release locks on $build_root");
my $timeout = time + 2;
while(time != $timeout and -d $build_root) { }
die "unable to delete '$build_root' in preparation of build because some process has a lock on it"
if -d $build_root;
}
return $build_root;
}
=method release
$zilla->release;
This method releases the distribution, probably by uploading it to the CPAN.
The actual effects of this method (as with most of the methods) is determined
by the loaded plugins.
=cut
sub release {
my $self = shift;
Carp::croak("you can't release without any Releaser plugins")
unless my @releasers = @{ $self->plugins_with(-Releaser) };
$ENV{DZIL_RELEASING} = 1;
my $tgz = $self->build_archive;
# call all plugins implementing BeforeRelease role
$_->before_release($tgz) for @{ $self->plugins_with(-BeforeRelease) };
# do the actual release
$_->release($tgz) for @releasers;
# call all plugins implementing AfterRelease role
$_->after_release($tgz) for @{ $self->plugins_with(-AfterRelease) };
}
=method clean
This method removes temporary files and directories suspected to have been
produced by the Dist::Zilla build process. Specifically, it deletes the
F<.build> directory and any entity that starts with the dist name and a hyphen,
like matching the glob C<Your-Dist-*>.
=cut
sub clean {
my ($self, $dry_run) = @_;
require File::Path;
for my $x (grep { -e } '.build', glob($self->name . '-*')) {
if ($dry_run) {
$self->log("clean: would remove $x");
} else {
$self->log("clean: removing $x");
File::Path::rmtree($x);
}
};
}
=method ensure_built_in_tmpdir
$zilla->ensure_built_in_tmpdir;
This method will consistently build the distribution in a temporary
subdirectory. It will return the path for the temporary build location.
=cut
sub ensure_built_in_tmpdir {
my $self = shift;
require File::Temp;
my $build_root = path('.build');
$build_root->mkpath unless -d $build_root;
my $target = path( File::Temp::tempdir(DIR => $build_root) );
$self->log("building distribution under $target for installation");
my $os_has_symlinks = eval { symlink("",""); 1 };
my $previous;
my $latest;
if( $os_has_symlinks ) {
$previous = path( $build_root, 'previous' );
$latest = path( $build_root, 'latest' );
if( -l $previous ) {
$previous->remove
or $self->log("cannot remove old .build/previous link");
}
if( -l $latest ) {
rename $latest, $previous
or $self->log("cannot move .build/latest link to .build/previous");
}
symlink $target->basename, $latest
or $self->log('cannot create link .build/latest');
}
$self->ensure_built_in($target);
return ($target, $latest, $previous);
}
=method install
$zilla->install( \%arg );
This method installs the distribution locally. The distribution will be built
in a temporary subdirectory, then the process will change directory to that
subdir and an installer will be run.
Valid arguments are:
keep_build_dir - if true, don't rmtree the build dir, even if everything
seemed to work
install_command - the command to run in the subdir to install the dist
default (roughly): $^X -MCPAN -einstall .
this argument should be an arrayref
=cut
sub install {
my ($self, $arg) = @_;
$arg ||= {};
my ($target, $latest) = $self->ensure_built_in_tmpdir;
my $ok = eval {
## no critic Punctuation
my $wd = File::pushd::pushd($target);
my @cmd = $arg->{install_command}
? @{ $arg->{install_command} }
: (cpanm => ".");
$self->log_debug([ 'installing via %s', \@cmd ]);
system(@cmd) && $self->log_fatal([ "error running %s", \@cmd ]);
1;
};
unless ($ok) {
my $error = $@ || '(exception clobered)';
$self->log("install failed, left failed dist in place at $target");
die $error;
}
if ($arg->{keep_build_dir}) {
$self->log("all's well; left dist in place at $target");
} else {
$self->log("all's well; removing $target");
$target->remove_tree({ safe => 0 });
$latest->remove if $latest;
}
return;
}
=method test
$zilla->test(\%arg);
This method builds a new copy of the distribution and tests it using
C<L</run_tests_in>>.
C<\%arg> may be omitted. Otherwise, valid arguments are:
keep_build_dir - if true, don't rmtree the build dir, even if everything
seemed to work
=cut
sub test {
my ($self, $arg) = @_;
Carp::croak("you can't test without any TestRunner plugins")
unless my @testers = @{ $self->plugins_with(-TestRunner) };
my ($target, $latest) = $self->ensure_built_in_tmpdir;
my $error = $self->run_tests_in($target, $arg);
if ($arg and $arg->{keep_build_dir}) {
$self->log("all's well; left dist in place at $target");
return;
}
$self->log("all's well; removing $target");
$target->remove_tree({ safe => 0 });
+ $latest->remove_tree({ safe => 0 }) if -d $latest; # error cannot unlink, is a directory
$latest->remove if $latest;
}
=method run_tests_in
my $error = $zilla->run_tests_in($directory, $arg);
This method runs the tests in $directory (a Path::Tiny), which must contain an
already-built copy of the distribution. It will throw an exception if there
are test failures.
It does I<not> set any of the C<*_TESTING> environment variables, nor
does it clean up C<$directory> afterwards.
=cut
sub run_tests_in {
my ($self, $target, $arg) = @_;
Carp::croak("you can't test without any TestRunner plugins")
unless my @testers = @{ $self->plugins_with(-TestRunner) };
for my $tester (@testers) {
my $wd = File::pushd::pushd($target);
$tester->test( $target, $arg );
}
}
=method run_in_build
$zilla->run_in_build( \@cmd );
This method makes a temporary directory, builds the distribution there,
executes all the dist's L<BuildRunner|Dist::Zilla::Role::BuildRunner>s
(unless directed not to, via C<< $arg->{build} = 0 >>), and
then runs the given command in the build directory. If the command exits
non-zero, the directory will be left in place.
=cut
sub run_in_build {
my ($self, $cmd, $arg) = @_;
$self->log_fatal("you can't build without any BuildRunner plugins")
unless ($arg and exists $arg->{build} and ! $arg->{build})
or @{ $self->plugins_with(-BuildRunner) };
require "Config.pm"; # skip autoprereq
my ($target, $latest) = $self->ensure_built_in_tmpdir;
my $abstarget = $target->absolute;
# building the dist for real
my $ok = eval {
my $wd = File::pushd::pushd($target);
if ($arg and exists $arg->{build} and ! $arg->{build}) {
system(@$cmd) and die "error while running: @$cmd";
return 1;
}
$self->_ensure_blib;
local $ENV{PERL5LIB} = join $Config::Config{path_sep},
(map { $abstarget->child('blib', $_) } qw(arch lib)),
(defined $ENV{PERL5LIB} ? $ENV{PERL5LIB} : ());
local $ENV{PATH} = join $Config::Config{path_sep},
(map { $abstarget->child('blib', $_) } qw(bin script)),
(defined $ENV{PATH} ? $ENV{PATH} : ());
system(@$cmd) and die "error while running: @$cmd";
1;
};
if ($ok) {
$self->log("all's well; removing $target");
$target->remove_tree({ safe => 0 });
$latest->remove if $latest;
} else {
my $error = $@ || '(unknown error)';
$self->log($error);
$self->log_fatal("left failed dist in place at $target");
}
}
# Ensures that a F<blib> directory exists in the build, by invoking all
# C<-BuildRunner> plugins to generate it. Useful for commands that operate on
# F<blib>, such as C<test> or C<run>.
sub _ensure_blib {
my ($self) = @_;
unless ( -d 'blib' ) {
my @builders = @{ $self->plugins_with( -BuildRunner ) };
$self->log_fatal("no BuildRunner plugins specified") unless @builders;
$_->build for @builders;
$self->log_fatal("no blib; failed to build properly?") unless -d 'blib';
}
}
__PACKAGE__->meta->make_immutable;
1;
diff --git a/t/plugins/gatherdir.t b/t/plugins/gatherdir.t
index 1778340..41a9d40 100644
--- a/t/plugins/gatherdir.t
+++ b/t/plugins/gatherdir.t
@@ -1,144 +1,144 @@
use strict;
use warnings;
use Test::More 0.88;
use ExtUtils::Manifest 'maniread';
use Test::DZil;
use Path::Tiny;
my $tzil = Builder->from_config(
{ dist_root => 'corpus/dist/DZT' },
{
add_files => {
'source/dist.ini' => simple_ini(
[ GatherDir => ],
[ GatherDir => BonusFiles => {
root => '../corpus/extra',
prefix => 'bonus',
} ],
[ GatherDir => DottyFiles => {
root => '../corpus/extra',
prefix => 'dotty',
include_dotfiles => 1,
} ],
[ GatherDir => Selective => {
root => '../corpus/extra',
prefix => 'some',
exclude_filename => [ 'notme.txt', 'subdir/index.html' ],
} ],
[ GatherDir => SelectiveMatch => {
root => '../corpus/extra',
prefix => 'xmatch',
exclude_match => [ 'notme\.*', '^subdir/index\.html$' ],
} ],
[ GatherDir => Symlinks => {
root => '../corpus/extra',
follow_symlinks => 1,
prefix => 'links',
} ],
[ GatherDir => PruneDirectory => {
root => '../corpus/extra',
prefix => 'pruned',
prune_directory => '^subdir$',
} ],
'Manifest',
'MetaConfig',
),
'source/.profile' => "Bogus dotfile.\n",
'corpus/extra/.dotfile' => "Bogus dotfile.\n",
'corpus/extra/notme.txt' => "A file to exclude.\n",
'source/.dotdir/extra/notme.txt' => "Another file to exclude.\n",
'source/extra/.dotdir/notme.txt' => "Another file to exclude.\n",
},
also_copy => { 'corpus/extra' => 'corpus/extra', 'corpus/global' => 'corpus/global' },
},
);
my $corpus_dir = path($tzil->tempdir)->child('corpus');
-if ($^O ne 'MSWin32') {
+if ($^O ne 'MSWin32' && $^O ne 'msys') {
symlink $corpus_dir->child('extra', 'vader.txt'), $corpus_dir->child('extra', 'vader_link.txt')
or note "could not create link: $!";
# link must be to something that is not otherwise being gathered, or we get duplicate errors
symlink $corpus_dir->child('global'), $corpus_dir->child('extra', 'global_link')
or note "could not create link: $!";
}
$tzil->chrome->logger->set_debug(1);
$tzil->build;
my @files = map {; $_->name } @{ $tzil->files };
is_filelist(
[ @files ],
[ qw(
bonus/subdir/index.html bonus/vader.txt bonus/notme.txt
dotty/subdir/index.html dotty/vader.txt dotty/.dotfile dotty/notme.txt
some/vader.txt
xmatch/vader.txt
links/vader.txt links/subdir/index.html links/notme.txt
pruned/notme.txt pruned/vader.txt
dist.ini lib/DZT/Sample.pm t/basic.t
MANIFEST
),
- ($^O ne 'MSWin32' ? ('links/global_link/config.ini') : ()),
- ($^O ne 'MSWin32' ? (map { $_ . '/vader_link.txt' } qw(bonus dotty some xmatch links pruned)) : ()),
+ ($^O ne 'MSWin32' && $^O ne 'msys' ? ('links/global_link/config.ini') : ()),
+ ($^O ne 'MSWin32' && $^O ne 'msys' ? (map { $_ . '/vader_link.txt' } qw(bonus dotty some xmatch links pruned)) : ()),
],
"GatherDir gathers all files in the source dir",
);
my $manifest = maniread($tzil->tempdir->child('build/MANIFEST')->stringify);
my $count = grep { exists $manifest->{$_} } @files;
ok($count == @files, "all files found were in manifest");
ok(keys(%$manifest) == @files, "all files in manifest were on disk");
diag 'got log messages: ', explain $tzil->log_messages
if not Test::Builder->new->is_passing;
my @to_remove;
TODO: {
- todo_skip('MSWin32 - skipping symlink test', 1) if $^O eq 'MSWin32';
+ todo_skip('MSWin32 - skipping symlink test', 1) if $^O eq 'MSWin32' || $^O eq 'msys';
# tmp/tmp -> tmp/private/tmp
my $real_tmp = path('tmp', 'private', 'tmp');
mkpath $real_tmp;
my $link_tmp = path('tmp', 'tmp');
symlink 'private/tmp', 'tmp/tmp';
push @to_remove, [ $real_tmp, $link_tmp ];
my $tzil = Builder->from_config(
{ dist_root => 'corpus/dist' },
{
add_files => {
'source/dist.ini' => simple_ini(
[ GatherDir => { root => 'DZ1' } ],
),
},
tempdir_root => 'tmp/tmp',
},
);
$tzil->chrome->logger->set_debug(1);
$tzil->build;
my @files = map {; $_->name } @{ $tzil->files };
is_filelist(
[ @files ],
[ qw(dist.ini lib/DZ1.pm) ],
"GatherDir gathers all files in the source dir (canonically corpus/dist/DZ1)",
);
diag 'got log messages: ', explain $tzil->log_messages
if not Test::Builder->new->is_passing;
}
for my $pair (@to_remove) {
$pair->[0]->remove_tree;
$pair->[1]->remove;
}
done_testing;
|
rjbs/Dist-Zilla
|
4948f65309fd30a3c69596352653d4502dd4f186
|
Changes: credit for package NAME v1.2.3
|
diff --git a/Changes b/Changes
index 86f1926..df32a3e 100644
--- a/Changes
+++ b/Changes
@@ -1,519 +1,521 @@
Revision history for {{$dist->name}}
{{$NEXT}}
- update some links to use https instead of http (thanks, Elvin
Aslanov)
- turn on strict and warnings in generated author tests (thanks, Mark
Flickinger)
+ - use "v1.2.3" for multi-dot versions in "package NAME VERSION" formats
+ (thanks, Branislav ZahradnÃk)
6.028 2022-11-09 10:54:14-05:00 America/New_York
- remove bogus work-in-progress signatures-using commit from 6.027;
that was a bad release! thanks for the heads-up about it to Gianni
"dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
4.300039 2013-09-20 06:05:10 Asia/Tokyo
- tweak metafile generator to keep CPAN::Meta validator happy (thanks,
David Golden)
4.300038 2013-09-08 09:18:34 America/New_York
- add horrible hack to avoid generating non-UTF-8 META.yml; seriously,
don't look at the code! Thanks, David Golden, whose code was simple
and probably much, much saner, but didn't cover as many cases as rjbs
wanted to cover.
4.300037 2013-08-28 21:43:36 America/New_York
- update repo and bugtacker URLs
4.300036 2013-08-25 21:41:21 America/New_York
|
rjbs/Dist-Zilla
|
ff13bd839161f6cfa572eddec24a79594937d1bb
|
Fix PkgVersion's use-package when multi-dot versioning is used
|
diff --git a/lib/Dist/Zilla/Plugin/PkgVersion.pm b/lib/Dist/Zilla/Plugin/PkgVersion.pm
index 8ad8534..68c97c9 100644
--- a/lib/Dist/Zilla/Plugin/PkgVersion.pm
+++ b/lib/Dist/Zilla/Plugin/PkgVersion.pm
@@ -1,375 +1,381 @@
package Dist::Zilla::Plugin::PkgVersion;
# ABSTRACT: add a $VERSION to your packages
use Moose;
with(
'Dist::Zilla::Role::FileMunger',
'Dist::Zilla::Role::FileFinderUser' => {
default_finders => [ ':InstallModules', ':ExecFiles' ],
},
'Dist::Zilla::Role::PPI',
);
use Dist::Zilla::Pragmas;
use namespace::autoclean;
=head1 SYNOPSIS
in dist.ini
[PkgVersion]
=head1 DESCRIPTION
This plugin will add lines like the following to each package in each Perl
module or program (more or less) within the distribution:
$MyModule::VERSION = '0.001';
or
{ our $VERSION = '0.001'; }
...where 0.001 is the version of the dist, and MyModule is the name of the
package being given a version. (In other words, it always uses fully-qualified
names to assign versions.)
It will skip any package declaration that includes a newline between the
C<package> keyword and the package name, like:
package
Foo::Bar;
This sort of declaration is also ignored by the CPAN toolchain, and is
typically used when doing monkey patching or other tricky things.
=attr die_on_existing_version
If true, then when PkgVersion sees an existing C<$VERSION> assignment, it will
throw an exception rather than skip the file. This attribute defaults to
false.
=attr die_on_line_insertion
By default, PkgVersion looks for a blank line after each C<package> statement.
If it finds one, it inserts the C<$VERSION> assignment on that line. If it
doesn't, it will insert a new line, which means the shipped copy of the module
will have different line numbers (off by one) than the source. If
C<die_on_line_insertion> is true, PkgVersion will raise an exception rather
than insert a new line.
=attr use_package
This option, if true, will not insert an assignment to C<$VERSION> but will
replace the existing C<package> declaration with one that includes a version
like:
package Module::Name 0.001;
=attr use_our
The idea here was to insert C<< { our $VERSION = '0.001'; } >> instead of C<<
$Module::Name::VERSION = '0.001'; >>. It turns out that this causes problems
with some analyzers. Use of this feature is deprecated.
Something else will replace it in the future.
=attr use_begin
If true, the version assignment is wrapped in a BEGIN block. This may help in
rare cases, such as when DynaLoader has to be called at BEGIN time, and
requires VERSION. This option should be needed rarely.
Also note that assigning to C<$VERSION> before the module has finished
compiling can lead to confused behavior with attempts to determine whether a
module was successfully loaded on perl v5.8.
=attr finder
=for stopwords FileFinder
This is the name of a L<FileFinder|Dist::Zilla::Role::FileFinder> for finding
modules to edit. The default value is C<:InstallModules> and C<:ExecFiles>;
this option can be used more than once.
Other predefined finders are listed in
L<Dist::Zilla::Role::FileFinderUser/default_finders>.
You can define your own with the
L<[FileFinder::ByName]|Dist::Zilla::Plugin::FileFinder::ByName> and
L<[FileFinder::Filter]|Dist::Zilla::Plugin::FileFinder::Filter> plugins.
=cut
sub BUILD {
my ($self) = @_;
$self->log("use_our option to PkgVersion is deprecated and will be removed")
if $self->use_our;
if ($self->use_package && ($self->use_our || $self->use_begin)) {
$self->log_fatal("use_package and (use_our or use_begin) are not compatible");
}
}
sub munge_files {
my ($self) = @_;
$self->munge_file($_) for @{ $self->found_files };
}
sub munge_file {
my ($self, $file) = @_;
if ($file->is_bytes) {
$self->log_debug($file->name . " has 'bytes' encoding, skipping...");
return;
}
if ($file->name =~ /\.pod$/) {
$self->log_debug($file->name . " is a pod file, skipping...");
return;
}
return $self->munge_perl($file);
}
has die_on_existing_version => (
is => 'ro',
isa => 'Bool',
default => 0,
);
has die_on_line_insertion => (
is => 'ro',
isa => 'Bool',
default => 0,
);
has use_package => (
is => 'ro',
isa => 'Bool',
default => 0,
);
has use_our => (
is => 'ro',
isa => 'Bool',
default => 0,
);
has use_begin => (
is => 'ro',
isa => 'Bool',
default => 0,
);
sub _version_assignment {
my ($self, $package, $version) = @_;
# the \x20 hack is here so that when we scan *this* document we don't find
# an assignment to version; it shouldn't be needed, but it's been annoying
# enough in the past that I'm keeping it here until tests are better
my $perl = $self->use_our
? "our \$VERSION\x20=\x20'$version';"
: "\$$package\::VERSION\x20=\x20'$version';";
return
$self->use_begin ? "BEGIN { $perl }"
: $self->use_our ? "{ $perl }"
: $perl;
}
sub munge_perl {
my ($self, $file) = @_;
my $version = $self->zilla->version;
require version;
Carp::croak("invalid characters in version")
unless version::is_lax($version);
my $document = $self->ppi_document_for_file($file);
my $package_stmts = $document->find('PPI::Statement::Package');
unless ($package_stmts) {
$self->log_debug([ 'skipping %s: no package statement found', $file->name ]);
return;
}
if ($self->document_assigns_to_variable($document, '$VERSION')) {
if ($self->die_on_existing_version) {
$self->log_fatal([ 'existing assignment to $VERSION in %s', $file->name ]);
}
$self->log([ 'skipping %s: assigns to $VERSION', $file->name ]);
return;
}
my %seen_pkg;
my $munged = 0;
STATEMENT: for my $stmt (@$package_stmts) {
my $package = $stmt->namespace;
if ($seen_pkg{ $package }++) {
$self->log([ 'skipping package re-declaration for %s', $package ]);
next;
}
if ($stmt->content =~ /package\s*(?:#.*)?\n\s*\Q$package/) {
$self->log([ 'skipping private package %s in %s', $package, $file->name ]);
next;
}
$self->log("non-ASCII package name is likely to cause problems")
if $package =~ /\P{ASCII}/;
$self->log("non-ASCII version is likely to cause problems")
if $version =~ /\P{ASCII}/;
if ($self->use_package) {
+ my $version_token = $version =~ m/\.\d+\./
+ ? PPI::Token::Number::Version->new(version->parse($version)->normal)
+ : PPI::Token::Number->new($version)
+ ;
+
if (my ($block) = grep {; $_->isa('PPI::Structure::Block') } $stmt->schildren) {
# Okay, we've encountered `package NAME BLOCK` and want to turn it into
# `package NAME VERSION BLOCK` but, to quote the PPI documentation,
# "we're on our own here".
#
# This will also preclude us from adding "# TRIAL" because where would
# it go? Look, a block package should (in my opinion) not be the only
# or top-level package in a file, so the TRIAL comment can be
# elsewhere. -- rjbs, 2021-06-12
#
# First off, let's make sure we do not already have a version. If the
# "version" has a "{" in it, it's just the block, and we're good.
# Otherwise, it's going to be a real version and we need to skip.
if ($stmt->version !~ /\{/) {
$self->log([
"skipping package %s with version %s declared",
$stmt->namespace,
$stmt->version,
]);
next STATEMENT;
}
# Okay, there's a block (which we have in $block) but no version. So,
- # we stick a Number in front of the block, then a space between them.
- $block->insert_before( PPI::Token::Number->new($version) );
+ # we stick a Number / Number::Version in front of the block, then a
+ # space between them.
+ $block->insert_before( $version_token );
$block->insert_before( PPI::Token::Whitespace->new(q{ }) );
$munged = 1;
next STATEMENT;
}
# Now, it's not got a block, but does it already have a version?
if (length $stmt->version) {
$self->log([
"skipping package %s with version %s declared",
$stmt->namespace,
$stmt->version,
]);
next STATEMENT;
}
# Oh, good! It's just a normal `package NAME` and we are going to add
# VERSION to it. This is stupid, but gets the job done.
- my $perl = sprintf 'package %s %s;', $package, $version;
+ my $perl = sprintf 'package %s %s;', $package, $version_token->content;
$perl .= ' # TRIAL' if $self->zilla->is_trial;
my $newstmt = PPI::Token::Unknown->new($perl);
Carp::carp("error inserting version in " . $file->name)
unless $stmt->parent->__replace_child($stmt, $newstmt);
$munged = 1;
next STATEMENT;
}
# the \x20 hack is here so that when we scan *this* document we don't find
# an assignment to version; it shouldn't be needed, but it's been annoying
# enough in the past that I'm keeping it here until tests are better
my $perl = $self->_version_assignment($package, $version);
$self->zilla->is_trial
and $perl .= ' # TRIAL';
my $clean_version = $version =~ tr/_//dr;
if ($version ne $clean_version) {
$perl .= "\n" . $self->_version_assignment($package, $clean_version);
}
$self->log_debug([
'adding $VERSION assignment to %s in %s',
$package,
$file->name,
]);
my $blank;
{
my $curr = $stmt;
while (1) {
# avoid bogus locations due to insert_after
$document->flush_locations if $munged;
my $curr_line_number = $curr->line_number + 1;
my $find = $document->find(sub {
my $line = $_[1]->line_number;
return $line > $curr_line_number ? undef : $line == $curr_line_number;
});
last unless $find and @$find == 1;
if ($find->[0]->isa('PPI::Token::Comment')) {
$curr = $find->[0];
next;
}
if ("$find->[0]" =~ /\A\s*\z/) {
$blank = $find->[0];
}
last;
}
}
$perl = $blank ? "$perl\n" : "\n$perl";
# Why can't I use PPI::Token::Unknown? -- rjbs, 2014-01-11
my $bogus_token = PPI::Token::Comment->new($perl);
if ($blank) {
Carp::carp("error inserting version in " . $file->name)
unless $blank->insert_after($bogus_token);
$blank->delete;
} else {
my $method = $self->die_on_line_insertion ? 'log_fatal' : 'log';
$self->$method([
'no blank line for $VERSION after package %s statement in %s line %s',
$stmt->namespace,
$file->name,
$stmt->line_number,
]);
Carp::carp("error inserting version in " . $file->name)
unless $stmt->insert_after($bogus_token);
}
$munged = 1;
}
# the document is no longer correct; it must be reparsed before it can be
# used again, so we can't just save_ppi_document_to_file
# Maybe we want a way to clear the cache for the old form, though...
# -- rjbs, 2016-04-24
$file->content($document->serialize) if $munged;
return;
}
__PACKAGE__->meta->make_immutable;
1;
=head1 SEE ALSO
Core Dist::Zilla plugins:
L<PodVersion|Dist::Zilla::Plugin::PodVersion>,
L<AutoVersion|Dist::Zilla::Plugin::AutoVersion>,
L<NextRelease|Dist::Zilla::Plugin::NextRelease>.
Other Dist::Zilla plugins:
L<OurPkgVersion|Dist::Zilla::Plugin::OurPkgVersion> inserts version
numbers using C<our $VERSION = '...';> and without changing line numbers
=cut
diff --git a/t/plugins/pkgversion.t b/t/plugins/pkgversion.t
index d5077ec..79d7400 100644
--- a/t/plugins/pkgversion.t
+++ b/t/plugins/pkgversion.t
@@ -1,626 +1,700 @@
use strict;
use warnings;
use Test::More 0.88;
use autodie;
use utf8;
use Test::DZil;
use Test::Fatal;
my $with_version = '
package DZT::WVer;
our $VERSION = 1.234;
1;
';
my $with_version_two_lines = '
package DZT::WVerTwoLines;
our $VERSION;
$VERSION = 1.234;
1;
';
my $with_version_fully_qualified = '
package DZT::WVerFullyQualified;
$DZT::WVerFullyQualified::VERSION = 1.234;
1;
';
my $use_our = '
package DZT::UseOur;
{ our $VERSION = \'1.234\'; }
1;
';
my $in_a_string_escaped = '
package DZT::WStrEscaped;
print "\$VERSION = 1.234;"
1;
';
my $xsloader_version = '
package DZT::XSLoader;
use XSLoader;
XSLoader::load __PACKAGE__, $DZT::XSLoader::VERSION;
1;
';
my $in_comment = '
package DZT::WInComment;
# our $VERSION = 1.234;
1;
';
my $in_comment_in_sub = '
package DZT::WInCommentInSub;
sub foo {
# our $VERSION = 1.234;
}
1;
';
my $in_pod_stm = '
package DZT::WInPODStm;
1;
END
our $VERSION = 1.234;
=for bug
# Because we have an END up there PPI considers this a statement
our $VERSION = 1.234;
=cut
'; $in_pod_stm =~ s/END/__END__/g;
my $two_packages = '
package DZT::TP1;
package DZT::TP2;
1;
';
my $repeated_packages = '
package DZT::R1;
package DZT::R2;
package DZT::R1;
1;
';
my $monkey_patched = '
package DZT::TP1;
package
DZT::TP2;
1;
';
my $hide_me_comment = '
package DZT::HMC;
package # hide me from toolchain
DZT::TP2;
1;
';
my $script = '
#!/usr/bin/perl
print "hello world\n";
';
my $script_pkg = '
#!/usr/bin/perl
package DZT::Script;
';
my $pod_with_pkg_trial = 'package DZT::PodWithPackageTrial;
=pod
=cut
';
my $pod_with_pkg = '
package DZT::PodWithPackage;
=pod
=cut
';
my $pod_with_utf8 = '
package DZT::PodWithUTF8;
our $Ï = atan2(1,1) * 4;
=pod
=cut
';
my $pod_no_pkg = '
=pod
=cut
';
my $pkg_version = '
package DZT::HasVersion 1.234;
my $x = 1;
';
my $pkg_block = '
package DZT::HasBlock {
my $x = 1;
}
';
my $pkg_version_block = '
package DZT::HasVersionAndBlock 1.234 {
my $x = 1;
}
';
{
my $tzil = Builder->from_config(
{ dist_root => 'corpus/dist/DZT' },
{
add_files => {
'source/lib/DZT/TP1.pm' => $two_packages,
'source/lib/DZT/WVer.pm' => $with_version,
'source/lib/DZT/WVerTwoLines.pm' => $with_version_two_lines,
'source/lib/DZT/WVerFullyQualified.pm' => $with_version_fully_qualified,
'source/lib/DZT/UseOur.pm' => $use_our,
'source/lib/DZT/WStrEscaped.pm' => $in_a_string_escaped,
'source/lib/DZT/XSLoader.pm' => $xsloader_version,
'source/lib/DZT/WInComment.pm' => $in_comment,
'source/lib/DZT/WInCommentInSub.pm' => $in_comment_in_sub,
'source/lib/DZT/WInPODStm.pm' => $in_pod_stm,
'source/lib/DZT/R1.pm' => $repeated_packages,
'source/lib/DZT/Monkey.pm' => $monkey_patched,
'source/lib/DZT/HideMe.pm' => $hide_me_comment,
'source/lib/DZT/PodWithPackage.pm' => $pod_with_pkg,
'source/lib/DZT/PodNoPackage.pm' => $pod_no_pkg,
'source/lib/DZT/PodWithUTF8.pm' => $pod_with_utf8,
'source/bin/script_pkg.pl' => $script_pkg,
'source/bin/script_ver.pl' => $script_pkg . "our \$VERSION = 1.234;\n",
'source/bin/script.pl' => $script,
'source/dist.ini' => simple_ini('GatherDir', 'PkgVersion', 'ExecDir'),
},
},
);
$tzil->build;
my $dzt_sample = $tzil->slurp_file('build/lib/DZT/Sample.pm');
like(
$dzt_sample,
qr{^\s*\$\QDZT::Sample::VERSION = '0.001';\E\s*$}m,
"added version to DZT::Sample",
);
my $dzt_tp1 = $tzil->slurp_file('build/lib/DZT/TP1.pm');
like(
$dzt_tp1,
qr{^\s*\$\QDZT::TP1::VERSION = '0.001';\E\s*$}m,
"added version to DZT::TP1",
);
like(
$dzt_tp1,
qr{^\s*\$\QDZT::TP2::VERSION = '0.001';\E\s*$}m,
"added version to DZT::TP2",
);
my $dzt_wver = $tzil->slurp_file('build/lib/DZT/WVer.pm');
unlike(
$dzt_wver,
qr{^\s*\$\QDZT::WVer::VERSION = '0.001';\E\s*$}m,
"*not* added to DZT::WVer; we have one already",
);
my $dzt_wver_two_lines = $tzil->slurp_file('build/lib/DZT/WVerTwoLines.pm');
unlike(
$dzt_wver_two_lines,
qr{^\s*\$\QDZT::WVerTwoLines::VERSION = '0.001';\E\s*$}m,
"*not* added to DZT::WVerTwoLines; we have one already",
);
my $dzt_wver_fully_qualified = $tzil->slurp_file('build/lib/DZT/WVerFullyQualified.pm');
unlike(
$dzt_wver_fully_qualified,
qr{^\s*\$\QDZT::WVerFullyQualified::VERSION = '0.001';\E\s*$}m,
"*not* added to DZT::WVerFullyQualified; we have one already",
);
my $dzt_use_our = $tzil->slurp_file('build/lib/DZT/UseOur.pm');
unlike(
$dzt_use_our,
qr{^\s*\$\QDZT::UseOur::VERSION = '0.001';\E\s*$}m,
"*not* added to DZT::UseOur; we have one already",
);
my $dzt_xsloader = $tzil->slurp_file('build/lib/DZT/XSLoader.pm');
like(
$dzt_xsloader,
qr{^\s*\$\QDZT::XSLoader::VERSION = '0.001';\E\s*$}m,
"added version to DZT::XSLoader",
);
my $dzt_wver_in_comment = $tzil->slurp_file('build/lib/DZT/WInComment.pm');
like(
$dzt_wver_in_comment,
qr{^\s*\$\QDZT::WInComment::VERSION = '0.001';\E\s*$}m,
"added to DZT::WInComment; the one we have is in a comment",
);
my $dzt_wver_in_comment_in_sub = $tzil->slurp_file('build/lib/DZT/WInCommentInSub.pm');
like(
$dzt_wver_in_comment_in_sub,
qr{^\s*\$\QDZT::WInCommentInSub::VERSION = '0.001';\E\s*$}m,
"added to DZT::WInCommentInSub; the one we have is in a comment",
);
my $dzt_wver_in_pod_stm = $tzil->slurp_file('build/lib/DZT/WInPODStm.pm');
like(
$dzt_wver_in_pod_stm,
qr{^\s*\$\QDZT::WInPODStm::VERSION = '0.001';\E\s*$}m,
"added to DZT::WInPODStm; the one we have is in some POD",
);
my $dzt_wver_str_escaped = $tzil->slurp_file('build/lib/DZT/WStrEscaped.pm');
like(
$dzt_wver_str_escaped,
qr{^\s*\$\QDZT::WStrEscaped::VERSION = '0.001';\E\s*$}m,
"added to DZT::WStrEscaped; the one we have is escaped",
);
my $dzt_script_pkg = $tzil->slurp_file('build/bin/script_pkg.pl');
like(
$dzt_script_pkg,
qr{^\s*\$\QDZT::Script::VERSION = '0.001';\E\s*$}m,
"added version to DZT::Script",
);
my $dzt_utf8 = $tzil->slurp_file('build/lib/DZT/PodWithUTF8.pm');
like(
$dzt_utf8,
qr{^\s*\$\QDZT::PodWithUTF8::VERSION = '0.001';\E\s*$}m,
"added version to DZT::PodWithUTF8",
);
TODO: {
local $TODO = 'only scanning for packages right now';
my $dzt_script = $tzil->slurp_file('build/bin/script.pl');
like(
$dzt_script,
qr{^\s*\$\QDZT::Script::VERSION = '0.001';\E\s*$}m,
"added version to plain script",
);
};
my $script_wver = $tzil->slurp_file('build/bin/script_ver.pl');
unlike(
$script_wver,
qr{^\s*\$\QDZT::WVer::VERSION = '0.001';\E\s*$}m,
"*not* added to versioned DZT::Script; we have one already",
);
ok(
grep({ m(skipping lib/DZT/WVer\.pm: assigns to \$VERSION) }
@{ $tzil->log_messages }),
"we report the reason for no updateing WVer",
);
my $dzt_r1 = $tzil->slurp_file('build/lib/DZT/R1.pm');
my @matches = grep { /R1::VER/ } split /\n/, $dzt_r1;
is(@matches, 1, "we add at most 1 VERSION per package");
my $dzt_monkey = $tzil->slurp_file('build/lib/DZT/Monkey.pm');
unlike(
$dzt_monkey,
qr{\$DZT::TP2::VERSION},
"no version for DZT::TP2 when it looks like a monkey patch"
);
ok(
grep({ m(skipping .+ DZT::TP2) } @{ $tzil->log_messages }),
"we report the reason for not updating Monkey",
);
my $dzt_hideme = $tzil->slurp_file('build/lib/DZT/HideMe.pm');
unlike(
$dzt_hideme,
qr{\$DZT::TP2::VERSION},
"no version for DZT::TP2 when it was hidden with a comment"
);
my $dzt_podwithpackage = $tzil->slurp_file('build/lib/DZT/PodWithPackage.pm');
like(
$dzt_podwithpackage,
qr{^\s*\$\QDZT::PodWithPackage::VERSION = '0.001';\E\s*$}m,
"added version to DZT::PodWithPackage",
);
my $dzt_podnopackage = $tzil->slurp_file('build/lib/DZT/PodNoPackage.pm');
unlike(
$dzt_podnopackage,
qr{VERSION},
"no version for pod files with no package declaration"
);
}
{
local $ENV{TRIAL} = 1;
my $tzil_trial = Builder->from_config(
{ dist_root => 'corpus/dist/DZT' },
{
add_files => {
'source/dist.ini' => simple_ini('GatherDir', 'PkgVersion', 'ExecDir'),
},
},
);
$tzil_trial->build;
my $dzt_sample_trial = $tzil_trial->slurp_file('build/lib/DZT/Sample.pm');
my $assignments = () = $dzt_sample_trial =~ /(DZT::Sample::VERSION =)/g;
is($assignments, 1, "we only add 1 VERSION assignment");
like(
$dzt_sample_trial,
qr{^\s*\$\QDZT::Sample::VERSION = '0.001'; # TRIAL\E\s*$}m,
"added version with 'TRIAL' comment when \$ENV{TRIAL}=1",
);
}
{
local $ENV{TRIAL} = 1;
my $tzil_trial = Builder->from_config(
{ dist_root => 'corpus/dist/DZT' },
{
add_files => {
'source/lib/DZT/PodWithPackageTrial.pm' => $pod_with_pkg_trial,
'source/dist.ini' => simple_ini(
{ # merge into root section
version => '0.004_002',
},
[ GatherDir => ],
[ PkgVersion => ],
),
},
},
);
$tzil_trial->build;
my $dzt_podwithpackagetrial = $tzil_trial->slurp_file('build/lib/DZT/PodWithPackageTrial.pm');
like(
$dzt_podwithpackagetrial,
qr{^\s*\$\QDZT::PodWithPackageTrial::VERSION = '0.004_002'; # TRIAL\E\s*.+^=pod}ms,
"added version to DZT::PodWithPackageTrial",
);
}
my $two_packages_weird = <<'END';
package DZT::TPW1;
{package DZT::TPW2;
sub tmp}
END
{
my $tzil2 = Builder->from_config(
{ dist_root => 'corpus/dist/DZT' },
{
add_files => {
'source/lib/DZT/TPW.pm' => $two_packages_weird,
'source/dist.ini' => simple_ini(
'GatherDir',
[ 'PkgVersion' => { die_on_line_insertion => 1, use_our => 1 } ],
),
},
},
);
$tzil2->build;
my $dzt_tpw = $tzil2->slurp_file('build/lib/DZT/TPW.pm');
like(
$dzt_tpw,
qr{^\s*\{ our \$VERSION = '0\.001'; \}\s*$}m,
"added 'our' version to DZT::TPW1",
);
like(
$dzt_tpw,
qr{^\s*\{ our \$VERSION = '0\.001'; \}\s*$}m,
"added 'our' version to DZT::TPW2",
);
}
{
my $tzil3 = Builder->from_config(
{ dist_root => 'corpus/dist/DZT' },
{
add_files => {
'source/dist.ini' => simple_ini(
'GatherDir',
[ 'PkgVersion' => 'first' ],
[ 'PkgVersion' => 'second' => { die_on_existing_version => 1 } ],
),
},
},
);
like(
exception { $tzil3->build },
qr/\[second\] existing assignment to \$VERSION in /,
'$VERSION inserted by the first plugin is detected by the second',
);
}
{
my $tzil4 = Builder->from_config(
{ dist_root => 'corpus/dist/DZT' },
{
add_files => {
'source/lib/DZT/TPW.pm' => $two_packages_weird,
'source/dist.ini' => simple_ini(
'GatherDir',
[ 'PkgVersion' => { use_begin => 1 } ],
),
},
},
);
$tzil4->build;
my $dzt_tpw4 = $tzil4->slurp_file('build/lib/DZT/TPW.pm');
like(
$dzt_tpw4,
qr{^\s*BEGIN\s*\{ \$DZT::TPW1::VERSION = '0\.001'; \}\s*$}m,
"added 'begin' version to DZT::TPW1",
);
}
-subtest "use_package" => sub {
+subtest "use_package with floating-number version" => sub {
my $tzil = Builder->from_config(
{ dist_root => 'corpus/dist/DZT' },
{
add_files => {
'source/lib/DZT/TPW.pm' => $two_packages_weird,
'source/lib/DZT/HasVersion.pm' => $pkg_version,
'source/lib/DZT/HasBlock.pm' => $pkg_block,
'source/lib/DZT/HasVersionAndBlock.pm' => $pkg_version_block,
'source/dist.ini' => simple_ini(
'GatherDir',
[ 'PkgVersion' => { use_package => 1 } ],
),
},
},
);
$tzil->build;
my $dzt_tpw = $tzil->slurp_file('build/lib/DZT/TPW.pm');
like(
$dzt_tpw,
qr{^package DZT::TPW1 0.001;$}m,
'we added "package NAME VERSION;" to code',
);
like(
$two_packages_weird,
qr{^package DZT::TPW1;$}m,
'input document had "package NAME;" to begin with',
);
unlike(
$dzt_tpw,
qr{^package DZT::TPW1;$}m,
"...but it's gone",
);
{
my $output = $tzil->slurp_file('build/lib/DZT/HasVersion.pm');
like(
$output,
qr{^package DZT::HasVersion 1\.234;$}m,
"package NAME VERSION: left untouched",
);
}
{
my $output = $tzil->slurp_file('build/lib/DZT/HasBlock.pm');
like(
$output,
qr/^package DZT::HasBlock 0\.001 \{$/m,
"package NAME BLOCK: version added",
);
like(
$output,
qr/my \$x = 1;/m,
"package NAME BLOCK: block intact",
);
}
{
my $output = $tzil->slurp_file('build/lib/DZT/HasVersionAndBlock.pm');
like(
$output,
qr/^package DZT::HasVersionAndBlock 1\.234 \{$/m,
"package NAME VERSION BLOCK: left untouched",
);
}
};
+subtest "use_package with multiple-dots version" => sub {
+ my $tzil = Builder->from_config(
+ { dist_root => 'corpus/dist/DZT' },
+ {
+ add_files => {
+ 'source/lib/DZT/TPW.pm' => $two_packages_weird,
+
+ 'source/lib/DZT/HasVersion.pm' => $pkg_version,
+ 'source/lib/DZT/HasBlock.pm' => $pkg_block,
+ 'source/lib/DZT/HasVersionAndBlock.pm' => $pkg_version_block,
+
+ 'source/dist.ini' => simple_ini(
+ { version => '0.0.1' },
+ 'GatherDir',
+ [ 'PkgVersion' => { use_package => 1 } ],
+ ),
+ },
+ },
+ );
+ $tzil->build;
+
+ my $dzt_tpw = $tzil->slurp_file('build/lib/DZT/TPW.pm');
+ like(
+ $dzt_tpw,
+ qr{^package DZT::TPW1 v0\.0\.1;$}m,
+ 'we added "package NAME VERSION;" to code',
+ );
+
+ like(
+ $two_packages_weird,
+ qr{^package DZT::TPW1;$}m,
+ 'input document had "package NAME;" to begin with',
+ );
+
+ unlike(
+ $dzt_tpw,
+ qr{^package DZT::TPW1;$}m,
+ "...but it's gone",
+ );
+
+ {
+ my $output = $tzil->slurp_file('build/lib/DZT/HasVersion.pm');
+ like(
+ $output,
+ qr{^package DZT::HasVersion 1\.234;$}m,
+ "package NAME VERSION: left untouched",
+ );
+ }
+
+ {
+ my $output = $tzil->slurp_file('build/lib/DZT/HasBlock.pm');
+ like(
+ $output,
+ qr/^package DZT::HasBlock v0\.0\.1 \{$/m,
+ "package NAME BLOCK: version added",
+ );
+ like(
+ $output,
+ qr/my \$x = 1;/m,
+ "package NAME BLOCK: block intact",
+ );
+ }
+
+ {
+ my $output = $tzil->slurp_file('build/lib/DZT/HasVersionAndBlock.pm');
+ like(
+ $output,
+ qr/^package DZT::HasVersionAndBlock 1\.234 \{$/m,
+ "package NAME VERSION BLOCK: left untouched",
+ );
+ }
+
+};
+
foreach my $use_our (0, 1) {
foreach my $use_begin (0, 1) {
my $tzil_trial = Builder->from_config(
{ dist_root => 'does-not-exist' },
{
add_files => {
'source/dist.ini' => simple_ini(
{ # merge into root section
version => '0.004_002',
},
[ GatherDir => ],
[ PkgVersion => {
use_our => $use_our,
use_begin => $use_begin,
} ],
),
'source/lib/DZT/Sample.pm' => "package DZT::Sample;\n1;\n",
},
},
);
$tzil_trial->build;
my $dzt_sample_trial = $tzil_trial->slurp_file('build/lib/DZT/Sample.pm');
my $want = $use_our ? (
$use_begin ? <<'MODULE'
BEGIN { our $VERSION = '0.004_002'; } # TRIAL
BEGIN { our $VERSION = '0.004002'; }
MODULE
: <<'MODULE'
{ our $VERSION = '0.004_002'; } # TRIAL
{ our $VERSION = '0.004002'; }
MODULE
)
: (
$use_begin ? <<'MODULE'
BEGIN { $DZT::Sample::VERSION = '0.004_002'; } # TRIAL
BEGIN { $DZT::Sample::VERSION = '0.004002'; }
MODULE
: <<'MODULE'
$DZT::Sample::VERSION = '0.004_002'; # TRIAL
$DZT::Sample::VERSION = '0.004002';
MODULE
);
is(
$dzt_sample_trial,
"package DZT::Sample;\n${want}1;\n",
"use_our = $use_our, use_begin = $use_begin: added version with 'TRIAL' comment and eval line when using an underscore trial version",
);
}
}
done_testing;
|
rjbs/Dist-Zilla
|
4a094039626b000efb3bb8311e5846eb4ddc9a12
|
Changes: note the changes to strict in generated tests
|
diff --git a/Changes b/Changes
index 41065d1..86f1926 100644
--- a/Changes
+++ b/Changes
@@ -1,517 +1,519 @@
Revision history for {{$dist->name}}
{{$NEXT}}
- update some links to use https instead of http (thanks, Elvin
Aslanov)
+ - turn on strict and warnings in generated author tests (thanks, Mark
+ Flickinger)
6.028 2022-11-09 10:54:14-05:00 America/New_York
- remove bogus work-in-progress signatures-using commit from 6.027;
that was a bad release! thanks for the heads-up about it to Gianni
"dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
4.300039 2013-09-20 06:05:10 Asia/Tokyo
- tweak metafile generator to keep CPAN::Meta validator happy (thanks,
David Golden)
4.300038 2013-09-08 09:18:34 America/New_York
- add horrible hack to avoid generating non-UTF-8 META.yml; seriously,
don't look at the code! Thanks, David Golden, whose code was simple
and probably much, much saner, but didn't cover as many cases as rjbs
wanted to cover.
4.300037 2013-08-28 21:43:36 America/New_York
- update repo and bugtacker URLs
4.300036 2013-08-25 21:41:21 America/New_York
|
rjbs/Dist-Zilla
|
f8b3d4eeaf9bd29683a31efebb9999bf91d5cdb0
|
enable strict in generated author tests
|
diff --git a/lib/Dist/Zilla/Plugin/MetaTests.pm b/lib/Dist/Zilla/Plugin/MetaTests.pm
index f52497b..3e6e6cf 100644
--- a/lib/Dist/Zilla/Plugin/MetaTests.pm
+++ b/lib/Dist/Zilla/Plugin/MetaTests.pm
@@ -1,56 +1,57 @@
package Dist::Zilla::Plugin::MetaTests;
# ABSTRACT: common extra tests for META.yml
use Moose;
extends 'Dist::Zilla::Plugin::InlineFiles';
with 'Dist::Zilla::Role::PrereqSource';
use Dist::Zilla::Pragmas;
use namespace::autoclean;
=head1 DESCRIPTION
This is an extension of L<Dist::Zilla::Plugin::InlineFiles>, providing the
following files:
xt/author/meta-yaml.t - a standard Test::CPAN::Meta test
L<Test::CPAN::Meta> will be added as a C<develop requires> dependency (which
can be installed via C<< dzil listdeps --author | cpanm >>).
=head1 SEE ALSO
Core Dist::Zilla plugins:
L<MetaResources|Dist::Zilla::Plugin::MetaResources>,
L<MetaNoIndex|Dist::Zilla::Plugin::MetaNoIndex>,
L<MetaYAML|Dist::Zilla::Plugin::MetaYAML>,
L<MetaJSON|Dist::Zilla::Plugin::MetaJSON>,
L<MetaConfig|Dist::Zilla::Plugin::MetaConfig>.
=cut
# Register the author test prereq as a "develop requires"
# so it will be listed in "dzil listdeps --author"
sub register_prereqs {
my ($self) = @_;
$self->zilla->register_prereqs(
{
phase => 'develop', type => 'requires',
},
'Test::CPAN::Meta' => 0,
);
}
__PACKAGE__->meta->make_immutable;
1;
__DATA__
___[ xt/author/distmeta.t ]___
#!perl
# This file was automatically generated by Dist::Zilla::Plugin::MetaTests.
-
+use strict;
+use warnings;
use Test::CPAN::Meta;
meta_yaml_ok();
diff --git a/lib/Dist/Zilla/Plugin/PodCoverageTests.pm b/lib/Dist/Zilla/Plugin/PodCoverageTests.pm
index 235fd34..18762cb 100644
--- a/lib/Dist/Zilla/Plugin/PodCoverageTests.pm
+++ b/lib/Dist/Zilla/Plugin/PodCoverageTests.pm
@@ -1,66 +1,67 @@
package Dist::Zilla::Plugin::PodCoverageTests;
# ABSTRACT: a author test for Pod coverage
use Moose;
extends 'Dist::Zilla::Plugin::InlineFiles';
with 'Dist::Zilla::Role::PrereqSource';
use Dist::Zilla::Pragmas;
use namespace::autoclean;
=head1 SYNOPSIS
# Add this line to dist.ini
[PodCoverageTests]
# Run this in the command line to test for POD coverage:
$ dzil test --release
=head1 DESCRIPTION
This is an extension of L<Dist::Zilla::Plugin::InlineFiles>, providing the
following files:
xt/author/pod-coverage.t - a standard Test::Pod::Coverage test
This test uses L<Pod::Coverage::TrustPod> to check your Pod coverage. This
means that to indicate that some subs should be treated as covered, even if no
documentation can be found, you can add:
=for Pod::Coverage sub_name other_sub this_one_too
L<Test::Pod::Coverage> C<1.08> and L<Pod::Coverage::TrustPod> will be added as
C<develop requires> dependencies.
One can run the release tests by invoking C<dzil test --release>.
=cut
# Register the author test prereq as a "develop requires"
# so it will be listed in "dzil listdeps --author"
sub register_prereqs {
my ($self) = @_;
$self->zilla->register_prereqs(
{
type => 'requires',
phase => 'develop',
},
'Test::Pod::Coverage' => '1.08',
'Pod::Coverage::TrustPod' => 0,
);
}
__PACKAGE__->meta->make_immutable;
1;
__DATA__
___[ xt/author/pod-coverage.t ]___
#!perl
# This file was automatically generated by Dist::Zilla::Plugin::PodCoverageTests.
-
+use strict;
+use warnings;
use Test::Pod::Coverage 1.08;
use Pod::Coverage::TrustPod;
all_pod_coverage_ok({ coverage_class => 'Pod::Coverage::TrustPod' });
|
rjbs/Dist-Zilla
|
c879638816a290d83f4ce1e43551796606fc0c9e
|
replace more http links with https
|
diff --git a/lib/Dist/Zilla.pm b/lib/Dist/Zilla.pm
index a8a5c8f..1431345 100644
--- a/lib/Dist/Zilla.pm
+++ b/lib/Dist/Zilla.pm
@@ -1,889 +1,885 @@
package Dist::Zilla;
# ABSTRACT: distribution builder; installer not included!
use Moose 0.92; # role composition fixes
with 'Dist::Zilla::Role::ConfigDumper';
use Dist::Zilla::Pragmas;
# This comment has fünÌnÌÿ characters.
use MooseX::Types::Moose qw(ArrayRef Bool HashRef Object Str);
use MooseX::Types::Perl qw(DistName LaxVersionStr);
use Moose::Util::TypeConstraints;
use Dist::Zilla::Types qw(Path License ReleaseStatus);
use Log::Dispatchouli 1.100712; # proxy_loggers, quiet_fatal
use Dist::Zilla::Path;
use List::Util 1.33 qw(first none);
use Software::License 0.104001; # ->program
use String::RewritePrefix;
use Try::Tiny;
use Dist::Zilla::Prereqs;
use Dist::Zilla::File::OnDisk;
use Dist::Zilla::Role::Plugin;
use Dist::Zilla::Util;
use Module::Runtime 'require_module';
use namespace::autoclean;
=head1 DESCRIPTION
Dist::Zilla builds distributions of code to be uploaded to the CPAN. In this
respect, it is like L<ExtUtils::MakeMaker>, L<Module::Build>, or
L<Module::Install>. Unlike those tools, however, it is not also a system for
installing code that has been downloaded from the CPAN. Since it's only run by
authors, and is meant to be run on a repository checkout rather than on
published, released code, it can do much more than those tools, and is free to
make much more ludicrous demands in terms of prerequisites.
If you have access to the web, you can learn more and find an interactive
-tutorial at B<L<dzil.org|http://dzil.org/>>. If not, try
+tutorial at B<L<dzil.org|https://dzil.org/>>. If not, try
L<Dist::Zilla::Tutorial>.
=cut
has chrome => (
is => 'rw',
isa => role_type('Dist::Zilla::Role::Chrome'),
required => 1,
);
=attr name
The name attribute (which is required) gives the name of the distribution to be
built. This is usually the name of the distribution's main module, with the
double colons (C<::>) replaced with dashes. For example: C<Dist-Zilla>.
=cut
has name => (
is => 'ro',
isa => DistName,
lazy => 1,
builder => '_build_name',
);
=attr version
This is the version of the distribution to be created.
=cut
has _version_override => (
isa => LaxVersionStr,
is => 'ro' ,
init_arg => 'version',
);
# XXX: *clearly* this needs to be really much smarter -- rjbs, 2008-06-01
has version => (
is => 'rw',
isa => LaxVersionStr,
lazy => 1,
init_arg => undef,
builder => '_build_version',
);
sub _build_name {
my ($self) = @_;
my $name;
for my $plugin (@{ $self->plugins_with(-NameProvider) }) {
next unless defined(my $this_name = $plugin->provide_name);
$self->log_fatal('attempted to set name twice') if defined $name;
$name = $this_name;
}
$self->log_fatal('no name was ever set') unless defined $name;
$name;
}
sub _build_version {
my ($self) = @_;
my $version = $self->_version_override;
for my $plugin (@{ $self->plugins_with(-VersionProvider) }) {
next unless defined(my $this_version = $plugin->provide_version);
$self->log_fatal('attempted to set version twice') if defined $version;
$version = $this_version;
}
$self->log_fatal('no version was ever set') unless defined $version;
$version;
}
=attr release_status
This attribute sets the release status to one of the
L<CPAN::META::Spec|https://metacpan.org/pod/CPAN::Meta::Spec#release_status>
values: 'stable', 'testing' or 'unstable'.
If the C<$ENV{RELEASE_STATUS}> environment variable exists, its value will
be used as the release status.
For backwards compatibility, if C<$ENV{RELEASE_STATUS}> does not exist and
the C<$ENV{TRIAL}> variable is true, the release status will be 'testing'.
Otherwise, the release status will be set from a
L<ReleaseStatusProvider|Dist::Zilla::Role::ReleaseStatusProvider>, if one
has been configured.
For backwards compatibility, setting C<is_trial> true in F<dist.ini> is
equivalent to using a C<ReleaseStatusProvider>. If C<is_trial> is false,
it has no effect.
Only B<one> C<ReleaseStatusProvider> may be used.
If no providers are used, the release status defaults to 'stable' unless there
is an "_" character in the version, in which case, it defaults to 'testing'.
=cut
# release status must be lazy, after files are gathered
has release_status => (
is => 'ro',
isa => ReleaseStatus,
lazy => 1,
builder => '_build_release_status',
);
sub _build_release_status {
my ($self) = @_;
# environment variables override completely
return $self->_release_status_from_env if $self->_release_status_from_env;
# other ways of setting status must not conflict
my $status;
# dist.ini is equivalent to a release provider if is_trial is true.
# If false, though, we want other providers to run or fall back to
# the version
$status = 'testing' if $self->_override_is_trial;
for my $plugin (@{ $self->plugins_with(-ReleaseStatusProvider) }) {
next unless defined(my $this_status = $plugin->provide_release_status);
$self->log_fatal('attempted to set release status twice')
if defined $status;
$status = $this_status;
}
return $status || ( $self->version =~ /_/ ? 'testing' : 'stable' );
}
# captures environment variables early during Zilla object construction
has _release_status_from_env => (
is => 'ro',
isa => Str,
builder => '_build_release_status_from_env',
);
sub _build_release_status_from_env {
my ($self) = @_;
return $ENV{RELEASE_STATUS} if $ENV{RELEASE_STATUS};
return $ENV{TRIAL} ? 'testing' : '';
}
=attr abstract
This is a one-line summary of the distribution. If none is given, one will be
looked for in the L</main_module> of the dist.
=cut
has abstract => (
is => 'rw',
isa => 'Str',
lazy => 1,
default => sub {
my ($self) = @_;
unless ($self->main_module) {
die "no abstract given and no main_module found; make sure your main module is in ./lib\n";
}
my $file = $self->main_module;
$self->log_debug("extracting distribution abstract from " . $file->name);
my $abstract = Dist::Zilla::Util->abstract_from_file($file);
if (!defined($abstract)) {
my $filename = $file->name;
die "Unable to extract an abstract from $filename. Please add the following comment to the file with your abstract:
# ABSTRACT: turns baubles into trinkets
";
}
return $abstract;
}
);
=attr main_module
This is the module where Dist::Zilla might look for various defaults, like
the distribution abstract. By default, it's derived from the distribution
name. If your distribution is Foo-Bar, and F<lib/Foo/Bar.pm> exists,
that's the main_module. Otherwise, it's the shortest-named module in the
distribution. This may change!
You can override the default by specifying the file path explicitly,
ie:
main_module = lib/Foo/Bar.pm
=cut
has _main_module_override => (
isa => 'Str',
is => 'ro' ,
init_arg => 'main_module',
predicate => '_has_main_module_override',
);
has main_module => (
is => 'ro',
isa => 'Dist::Zilla::Role::File',
lazy => 1,
init_arg => undef,
default => sub {
my ($self) = @_;
my $file;
my $guess;
if ( $self->_has_main_module_override ) {
$file = first { $_->name eq $self->_main_module_override }
@{ $self->files };
} else {
# We're having to guess
$guess = $self->name =~ s{-}{/}gr;
$guess = "lib/$guess.pm";
$file = (first { $_->name eq $guess } @{ $self->files })
|| (sort { length $a->name <=> length $b->name }
grep { $_->name =~ m{\.pm\z} and $_->name =~ m{\Alib/} }
@{ $self->files })[0];
$self->log("guessing dist's main_module is " . ($file ? $file->name : $guess));
}
if (not $file) {
my @errorlines;
push @errorlines, "Unable to find main_module in the distribution";
if ($self->_has_main_module_override) {
push @errorlines, "'main_module' was specified in dist.ini but the file '" . $self->_main_module_override . "' is not to be found in our dist. ( Did you add it? )";
} else {
push @errorlines,"We tried to guess '$guess' but no file like that existed";
}
if (not @{ $self->files }) {
push @errorlines, "Upon further inspection we didn't find any files in your dist, did you add any?";
} elsif ( none { $_->name =~ m{^lib/.+\.pm\z} } @{ $self->files } ){
push @errorlines, "We didn't find any .pm files in your dist, this is probably a problem.";
}
push @errorlines,"Cannot continue without a main_module";
$self->log_fatal( join qq{\n}, @errorlines );
}
$self->log_debug("dist's main_module is " . $file->name);
return $file;
},
);
=attr license
This is the L<Software::License|Software::License> object for this dist's
license and copyright.
It will be created automatically, if possible, with the
C<copyright_holder> and C<copyright_year> attributes. If necessary, it will
try to guess the license from the POD of the dist's main module.
A better option is to set the C<license> name in the dist's config to something
understandable, like C<Perl_5>.
=cut
has license => (
is => 'ro',
isa => License,
lazy => 1,
init_arg => 'license_obj',
predicate => '_has_license',
builder => '_build_license',
handles => {
copyright_holder => 'holder',
copyright_year => 'year',
},
);
sub _build_license {
my ($self) = @_;
my $license_class = $self->_license_class;
my $copyright_holder = $self->_copyright_holder;
my $copyright_year = $self->_copyright_year;
my $provided_license;
for my $plugin (@{ $self->plugins_with(-LicenseProvider) }) {
my $this_license = $plugin->provide_license({
copyright_holder => $copyright_holder,
copyright_year => $copyright_year,
});
next unless defined $this_license;
$self->log_fatal('attempted to set license twice')
if defined $provided_license;
$provided_license = $this_license;
}
return $provided_license if defined $provided_license;
if ($license_class) {
$license_class = String::RewritePrefix->rewrite(
{
'=' => '',
'' => 'Software::License::'
},
$license_class,
);
} else {
require Software::LicenseUtils;
my @guess = Software::LicenseUtils->guess_license_from_pod(
$self->main_module->content
);
if (@guess != 1) {
$self->log_fatal(
"no license data in config, no %Rights stash,",
"couldn't make a good guess at license from Pod; giving up. ",
"Perhaps you need to set up a global config file (dzil setup)?"
);
}
my $filename = $self->main_module->name;
$license_class = $guess[0];
$self->log("based on POD in $filename, guessing license is $guess[0]");
}
unless (eval { require_module($license_class) }) {
$self->log_fatal(
"could not load class $license_class for license " . $self->_license_class
);
}
my $license = $license_class->new({
holder => $self->_copyright_holder,
year => $self->_copyright_year,
program => $self->name,
});
$self->_clear_license_class;
$self->_clear_copyright_holder;
$self->_clear_copyright_year;
return $license;
}
has _license_class => (
is => 'ro',
isa => 'Maybe[Str]',
lazy => 1,
init_arg => 'license',
clearer => '_clear_license_class',
default => sub {
my $stash = $_[0]->stash_named('%Rights');
$stash && return $stash->license_class;
return;
}
);
has _copyright_holder => (
is => 'ro',
isa => 'Maybe[Str]',
lazy => 1,
init_arg => 'copyright_holder',
clearer => '_clear_copyright_holder',
default => sub {
return unless my $stash = $_[0]->stash_named('%Rights');
$stash && return $stash->copyright_holder;
return;
}
);
has _copyright_year => (
is => 'ro',
isa => 'Str',
lazy => 1,
init_arg => 'copyright_year',
clearer => '_clear_copyright_year',
default => sub {
# Oh man. This is a terrible idea! I mean, what if by the code gets run
# around like Dec 31, 23:59:59.9 and by the time the default gets called
# it's the next year but the default was already set up? Oh man. That
# could ruin lives! I guess we could make this a sub to defer the guess,
# but think of the performance hit! I guess we'll have to suffer through
# this until we can optimize the code to not take .1s to run, right? --
# rjbs, 2008-06-13
my $stash = $_[0]->stash_named('%Rights');
my $year = $stash && $stash->copyright_year;
return( $year // (localtime)[5] + 1900 );
}
);
=attr authors
This is an arrayref of author strings, like this:
[
'Ricardo Signes <[email protected]>',
'X. Ample, Jr <[email protected]>',
]
This is likely to change at some point in the near future.
=cut
has authors => (
is => 'ro',
isa => ArrayRef[Str],
lazy => 1,
default => sub {
my ($self) = @_;
if (my $stash = $self->stash_named('%User')) {
return $stash->authors;
}
my $author = try { $self->copyright_holder };
return [ $author ] if length $author;
$self->log_fatal(
"No %User stash and no copyright holder;",
"can't determine dist author; configure author or a %User section",
);
},
);
=attr files
This is an arrayref of objects implementing L<Dist::Zilla::Role::File> that
will, if left in this arrayref, be built into the dist.
Non-core code should avoid altering this arrayref, but sometimes there is not
other way to change the list of files. In the future, the representation used
for storing files B<will be changed>.
=cut
has files => (
is => 'ro',
isa => ArrayRef[ role_type('Dist::Zilla::Role::File') ],
lazy => 1,
init_arg => undef,
default => sub { [] },
);
sub prune_file {
my ($self, $file) = @_;
my @files = @{ $self->files };
for my $i (0 .. $#files) {
next unless $file == $files[ $i ];
splice @{ $self->files }, $i, 1;
return;
}
return;
}
=attr root
This is the root directory of the dist, as a L<Path::Tiny>. It will
nearly always be the current working directory in which C<dzil> was run.
=cut
has root => (
is => 'ro',
isa => Path,
coerce => 1,
required => 1,
);
=attr is_trial
This attribute tells us whether or not the dist will be a trial release,
i.e. whether it has C<release_status> 'testing' or 'unstable'.
Do not set this directly, it will be derived from C<release_status>.
=cut
has is_trial => (
is => 'ro',
isa => Bool,
init_arg => undef,
lazy => 1,
builder => '_build_is_trial',
);
has _override_is_trial => (
is => 'ro',
isa => Bool,
init_arg => 'is_trial',
default => 0,
);
sub _build_is_trial {
my ($self) = @_;
return $self->release_status =~ /\A(?:testing|unstable)\z/ ? 1 : 0;
}
=attr plugins
This is an arrayref of plugins that have been plugged into this Dist::Zilla
object.
Non-core code B<must not> alter this arrayref. Public access to this attribute
B<may go away> in the future.
=cut
has plugins => (
is => 'ro',
isa => 'ArrayRef[Dist::Zilla::Role::Plugin]',
init_arg => undef,
default => sub { [ ] },
);
=attr distmeta
This is a hashref containing the metadata about this distribution that will be
stored in META.yml or META.json. You should not alter the metadata in this
hash; use a MetaProvider plugin instead.
=cut
has distmeta => (
is => 'ro',
isa => 'HashRef',
init_arg => undef,
lazy => 1,
builder => '_build_distmeta',
);
sub _build_distmeta {
my ($self) = @_;
require CPAN::Meta::Merge;
my $meta_merge = CPAN::Meta::Merge->new(default_version => 2);
my $meta = {};
for (@{ $self->plugins_with(-MetaProvider) }) {
$meta = $meta_merge->merge($meta, $_->metadata);
}
my %meta_main = (
'meta-spec' => {
version => 2,
url => 'https://metacpan.org/pod/CPAN::Meta::Spec',
},
name => $self->name,
version => $self->version,
abstract => $self->abstract,
author => $self->authors,
license => [ $self->license->meta2_name ],
release_status => $self->release_status,
dynamic_config => 0, # problematic, I bet -- rjbs, 2010-06-04
generated_by => $self->_metadata_generator_id
. ' version '
. ($self->VERSION // '(undef)'),
x_generated_by_perl => "$^V", # v5.24.0
);
if (my $spdx = $self->license->spdx_expression) {
$meta_main{x_spdx_expression} = $spdx;
}
$meta = $meta_merge->merge($meta, \%meta_main);
return $meta;
}
sub _metadata_generator_id { 'Dist::Zilla' }
=attr prereqs
This is a L<Dist::Zilla::Prereqs> object, which is a thin layer atop
L<CPAN::Meta::Prereqs>, and describes the distribution's prerequisites.
=method register_prereqs
Allows registration of prerequisites; delegates to
L<Dist::Zilla::Prereqs/register_prereqs> via our L</prereqs> attribute.
=cut
has prereqs => (
is => 'ro',
isa => 'Dist::Zilla::Prereqs',
init_arg => undef,
lazy => 1,
default => sub { Dist::Zilla::Prereqs->new },
handles => [ qw(register_prereqs) ],
);
=method plugin_named
my $plugin = $zilla->plugin_named( $plugin_name );
=cut
sub plugin_named {
my ($self, $name) = @_;
my $plugin = first { $_->plugin_name eq $name } @{ $self->plugins };
return $plugin if $plugin;
return;
}
=method plugins_with
my $roles = $zilla->plugins_with( -SomeRole );
This method returns an arrayref containing all the Dist::Zilla object's plugins
that perform the named role. If the given role name begins with a dash, the
dash is replaced with "Dist::Zilla::Role::"
=cut
sub plugins_with {
my ($self, $role) = @_;
$role =~ s/^-/Dist::Zilla::Role::/;
my $plugins = [ grep { $_->does($role) } @{ $self->plugins } ];
return $plugins;
}
=method find_files
my $files = $zilla->find_files( $finder_name );
This method will look for a
L<FileFinder|Dist::Zilla::Role::FileFinder>-performing plugin with the given
name and return the result of calling C<find_files> on it. If no plugin can be
found, an exception will be raised.
=cut
sub find_files {
my ($self, $finder_name) = @_;
$self->log_fatal("no plugin named $finder_name found")
unless my $plugin = $self->plugin_named($finder_name);
$self->log_fatal("plugin $finder_name is not a FileFinder")
unless $plugin->does('Dist::Zilla::Role::FileFinder');
$plugin->find_files;
}
sub _check_dupe_files {
my ($self) = @_;
my %files_named;
my @dupes;
for my $file (@{ $self->files }) {
my $filename = $file->name;
if (my $seen = $files_named{ $filename }) {
push @{ $seen }, $file;
push @dupes, $filename if @{ $seen } == 2;
} else {
$files_named{ $filename } = [ $file ];
}
}
return unless @dupes;
for my $name (@dupes) {
$self->log("attempt to add $name multiple times; added by: "
. join('; ', map { $_->added_by } @{ $files_named{ $name } })
);
}
Carp::croak("aborting; duplicate files would be produced");
}
sub _write_out_file {
my ($self, $file, $build_root) = @_;
# Okay, this is a bit much, until we have ->debug. -- rjbs, 2008-06-13
# $self->log("writing out " . $file->name);
my $file_path = path($file->name);
my $to_dir = path($build_root)->child( $file_path->parent );
my $to = $to_dir->child( $file_path->basename );
$to_dir->mkpath unless -e $to_dir;
die "not a directory: $to_dir" unless -d $to_dir;
Carp::croak("attempted to write $to multiple times") if -e $to;
path("$to")->spew_raw( $file->encoded_content );
chmod $file->mode, "$to" or die "couldn't chmod $to: $!";
}
=attr logger
This attribute stores a L<Log::Dispatchouli::Proxy> object, used to log
messages. By default, a proxy to the dist's L<Chrome|Dist::Zilla::Role::Chrome> is
taken.
The following methods are delegated from the Dist::Zilla object to the logger:
=for :list
* log
* log_debug
* log_fatal
=cut
has logger => (
is => 'ro',
isa => 'Log::Dispatchouli::Proxy', # could be duck typed, I guess
lazy => 1,
handles => [ qw(log log_debug log_fatal) ],
default => sub {
$_[0]->chrome->logger->proxy({ proxy_prefix => '[DZ] ' })
},
);
around dump_config => sub {
my ($orig, $self) = @_;
my $config = $self->$orig;
$config->{is_trial} = $self->is_trial;
return $config;
};
has _local_stashes => (
is => 'ro',
isa => HashRef[ Object ],
lazy => 1,
default => sub { {} },
);
has _global_stashes => (
is => 'ro',
isa => HashRef[ Object ],
lazy => 1,
default => sub { {} },
);
=method stash_named
my $stash = $zilla->stash_named( $name );
This method will return the stash with the given name, or undef if none exists.
It looks for a local stash (for this dist) first, then falls back to a global
stash (from the user's global configuration).
=cut
sub stash_named {
my ($self, $name) = @_;
return $self->_local_stashes->{ $name } if $self->_local_stashes->{$name};
return $self->_global_stashes->{ $name };
}
__PACKAGE__->meta->make_immutable;
1;
=head1 STABILITY PROMISE
None.
I will try not to break things within any major release. Minor releases are
not extensively tested before release. In major releases, anything goes,
although I will try to publish a complete list of known breaking changes in any
major release.
If Dist::Zilla was a tool, it would have yellow and black stripes and there
would be no L<UL
certification|https://en.wikipedia.org/wiki/UL_(safety_organization)> on it.
It is nasty, brutish, and large.
=head1 SUPPORT
There are usually people on C<irc.perl.org> in C<#distzilla>, even if they're
idling.
-The L<Dist::Zilla website|http://dzil.org/> has several valuable resources for
+The L<Dist::Zilla website|https://dzil.org/> has several valuable resources for
learning to use Dist::Zilla.
-There is a mailing list to discuss Dist::Zilla. You can L<join the
-list|http://www.listbox.com/subscribe/?list_id=139292> or L<browse the
-archives|http://listbox.com/member/archive/139292>.
-
=head1 SEE ALSO
=over 4
=item *
In the Dist::Zilla distribution:
=over 4
=item *
Plugin bundles:
L<@Basic|Dist::Zilla::PluginBundle::Basic>,
L<@Filter|Dist::Zilla::PluginBundle::Filter>.
=item *
Major plugins:
L<GatherDir|Dist::Zilla::Plugin::GatherDir>,
L<Prereqs|Dist::Zilla::Plugin::Prereqs>,
L<AutoPrereqs|Dist::Zilla::Plugin::AutoPrereqs>,
L<MetaYAML|Dist::Zilla::Plugin::MetaYAML>,
L<MetaJSON|Dist::Zilla::Plugin::MetaJSON>,
...
=back
=item *
On the CPAN:
=over 4
=item *
Search for plugins: L<https://metacpan.org/search?q=Dist::Zilla::Plugin::>
=item *
Search for plugin bundles: L<https://metacpan.org/search?q=Dist::Zilla::PluginBundle::>
=back
=back
diff --git a/lib/Dist/Zilla/Plugin/MetaResources.pm b/lib/Dist/Zilla/Plugin/MetaResources.pm
index f3a468b..07e53ec 100644
--- a/lib/Dist/Zilla/Plugin/MetaResources.pm
+++ b/lib/Dist/Zilla/Plugin/MetaResources.pm
@@ -1,84 +1,84 @@
package Dist::Zilla::Plugin::MetaResources;
# ABSTRACT: provide arbitrary "resources" for distribution metadata
use Moose;
with 'Dist::Zilla::Role::MetaProvider';
use Dist::Zilla::Pragmas;
use namespace::autoclean;
=head1 DESCRIPTION
This plugin adds resources entries to the distribution's metadata.
[MetaResources]
- homepage = http://example.com/~dude/project.asp
+ homepage = https://example.com/~dude/project.asp
bugtracker.web = https://rt.cpan.org/Public/Dist/Display.html?Name=Project
bugtracker.mailto = [email protected]
repository.url = git://github.com/dude/project.git
- repository.web = http://github.com/dude/project
+ repository.web = https://github.com/dude/project
repository.type = git
=cut
has resources => (
is => 'ro',
isa => 'HashRef',
required => 1,
);
around BUILDARGS => sub {
my $orig = shift;
my ($class, @arg) = @_;
my $args = $class->$orig(@arg);
my %copy = %{ $args };
my $zilla = delete $copy{zilla};
my $name = delete $copy{plugin_name};
if (exists $copy{license} && ref($copy{license}) ne 'ARRAY') {
$copy{license} = [ $copy{license} ];
}
if (exists $copy{bugtracker}) {
my $tracker = delete $copy{bugtracker};
$copy{bugtracker}{web} = $tracker;
}
if (exists $copy{repository}) {
my $repo = delete $copy{repository};
$copy{repository}{url} = $repo;
}
for my $multi (qw( bugtracker repository )) {
for my $key (grep { /^\Q$multi\E\./ } keys %copy) {
my $subkey = (split /\./, $key, 2)[1];
$copy{$multi}{$subkey} = delete $copy{$key};
}
}
return {
zilla => $zilla,
plugin_name => $name,
resources => \%copy,
};
};
sub metadata {
my ($self) = @_;
return { resources => $self->resources };
}
__PACKAGE__->meta->make_immutable;
1;
=head1 SEE ALSO
Dist::Zilla roles: L<MetaProvider|Dist::Zilla::Role::MetaProvider>.
Dist::Zilla plugins on the CPAN: L<GithubMeta|Dist::Zilla::Plugin::GithubMeta>.
=cut
diff --git a/lib/Dist/Zilla/Tutorial.pm b/lib/Dist/Zilla/Tutorial.pm
index f37531b..f206559 100644
--- a/lib/Dist/Zilla/Tutorial.pm
+++ b/lib/Dist/Zilla/Tutorial.pm
@@ -1,137 +1,137 @@
package Dist::Zilla::Tutorial;
# ABSTRACT: how to use this "Dist::Zilla" thing
use Dist::Zilla::Pragmas;
use Carp ();
Carp::confess "you're not meant to use the tutorial, just read it!";
1;
=head1 SYNOPSIS
B<BEFORE YOU GET STARTED>: Maybe you should be looking at the web-based
-tutorial instead. It's more complete. L<http://dzil.org/tutorial/start.html>
+tutorial instead. It's more complete. L<https://dzil.org/tutorial/start.html>
Dist::Zilla builds distributions to be uploaded to the CPAN. That means that
the first thing you'll need is some code.
Once you've got that, you'll need to configure Dist::Zilla. Here's a simple
F<dist.ini>:
name = Carbon-Dating
version = 0.003
author = Alan Smithee <[email protected]>
license = Perl_5
copyright_holder = Alan Smithee
[@Basic]
[Prereqs]
App::Cmd = 0.013
Number::Nary = 0
Sub::Exporter = 0.981
The topmost section configures Dist::Zilla itself. Here are some of the
entries it expects:
name - (required) the name of the dist being built
version - (required) the version of the dist
abstract - (required) a short description of the dist
author - (optional) the dist author (you may have multiple entries for this)
license - (required) the dist license; must be a Software::License::* name
copyright_holder - (required) the entity holding copyright on the dist
Some of the required values above may actually be provided by means other than
the top-level section of the config. For example,
L<VersionProvider|Dist::Zilla::Role::VersionProvider> plugins can
set the version, and a line like this in the "main module" of the dist will set
the abstract:
# ABSTRACT: a totally cool way to do totally great stuff
The main modules is the module that shares the same name as the dist, in
general.
Named sections load plugins, with the following rules:
If a section name begins with an equals sign (C<=>), the rest of the section
name is left intact and not expanded. If the section name begins with an at
sign (C<@>), it is prepended with C<Dist::Zilla::PluginBundle::>. Otherwise,
it is prepended with C<Dist::Zilla::Plugin::>.
The values inside a section are given as configuration to the plugin. Consult
each plugin's documentation for more information.
The "Basic" bundle, seen above, builds a fairly normal distribution. It
rewrites tests from F<./xt>, adds some information to POD, and builds a
F<Makefile.PL>. For more information, you can look at the docs for
L<@Basic|Dist::Zilla::PluginBundle::Basic> and see the plugins it includes.
=head1 BUILDING YOUR DIST
Maybe we're getting ahead of ourselves, here. Configuring a bunch of plugins
won't do you a lot of good unless you know how to use them to build your dist.
Dist::Zilla ships with a command called F<dzil> that will get installed by
default. While it can be extended to offer more commands, there are two really
useful ones:
$ dzil build
The C<build> command will build the distribution. Say you're using the
configuration in the SYNOPSIS above. You'll end up with a file called
F<Carbon-Dating-0.004.tar.gz>. As long as you've done everything right, it
will be suitable for uploading to the CPAN.
Of course, you should really test it out first. You can test the dist you'd be
building by running another F<dzil> command:
$ dzil test
This will build a new copy of your distribution and run its tests, so you'll
know whether the dist that C<build> would build is worth releasing!
=head1 HOW BUILDS GET BUILT
This is really more of a sketchy overview than a spec.
First, all the plugins that perform the
L<BeforeBuild|Dist::Zilla::Role::BeforeBuild> perform their C<before_build>
tasks.
The build root (where the dist is being built) is made.
The L<FileGatherer|Dist::Zilla::Role::FileGatherer>s gather and inject files
into the distribution, then the L<FilePruner|Dist::Zilla::Role::FilePruner>s
remove some of them.
All the L<FileMunger|Dist::Zilla::Role::FileMunger>s get a chance to muck about
with each file, possibly changing its name, content, or installability.
Now that the distribution is basically set up, it needs an install tool, like a
F<Makefile.PL>. All the
L<InstallTool|Dist::Zilla::Role::InstallTool>-performing plugins are used to
do whatever is needed to make the dist installable.
Everything is just about done. The files are all written out to disk and the
L<AfterBuild|Dist::Zilla::Role::AfterBuild> plugins do their thing.
=head1 RELEASING YOUR DIST
By running C<dzil release>, you'll test your
distribution, build a tarball of it, and upload it to the CPAN. Plugins are
able to do things like check your version control system to make sure you're
releasing a new version and that you tag the version you've just uploaded. It
can also update your Changelog file, too, making sure that you don't need to
know what your next version number will be before releasing.
The final CPAN release process is implemented by the
L<UploadToCPAN|Dist::Zilla::Plugin::UploadToCPAN> plugin. However you can
replace it by your own to match your own (company?) process.
=head1 SEE ALSO
L<dzil>
=cut
|
rjbs/Dist-Zilla
|
49b0e762acefb98ca54d37ef8dfa0551f00bf814
|
dzil: replace an http link with an https link
|
diff --git a/bin/dzil b/bin/dzil
index 9958c3b..3f971f2 100755
--- a/bin/dzil
+++ b/bin/dzil
@@ -1,21 +1,20 @@
#!/usr/bin/perl
-package
- dzil;
+package dzil;
use Dist::Zilla::App;
use Dist::Zilla::Pragmas;
# Let dzil --version know what to report:
$main::VERSION = $Dist::Zilla::App::VERSION;
# PODNAME: dzil
# ABSTRACT: do stuff with your dist
Dist::Zilla::App->run;
=head1 OVERVIEW
-For help with L<Dist::Zilla|Dist::Zilla>, start with L<http://dzil.org/> or
+For help with L<Dist::Zilla|Dist::Zilla>, start with L<https://dzil.org/> or
by running C<dzil commands>.
=cut
|
rjbs/Dist-Zilla
|
25ce9c112dbde8068ba1768ec1a3602fd9727e56
|
v6.028
|
diff --git a/Changes b/Changes
index 3292ba6..a26b793 100644
--- a/Changes
+++ b/Changes
@@ -1,515 +1,517 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+
+6.028 2022-11-09 10:54:14-05:00 America/New_York
- remove bogus work-in-progress signatures-using commit from 6.027;
that was a bad release! thanks for the heads-up about it to Gianni
"dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
4.300039 2013-09-20 06:05:10 Asia/Tokyo
- tweak metafile generator to keep CPAN::Meta validator happy (thanks,
David Golden)
4.300038 2013-09-08 09:18:34 America/New_York
- add horrible hack to avoid generating non-UTF-8 META.yml; seriously,
don't look at the code! Thanks, David Golden, whose code was simple
and probably much, much saner, but didn't cover as many cases as rjbs
wanted to cover.
4.300037 2013-08-28 21:43:36 America/New_York
- update repo and bugtacker URLs
4.300036 2013-08-25 21:41:21 America/New_York
- read CPAN::Uploader config with CPAN::Uploader, to work with new
trial releases supporting encrypted credential (thanks, Mike Doherty)
|
rjbs/Dist-Zilla
|
238ddd74d4c6c1f6a7f5cc908ee7bacada1beb23
|
prep next release
|
diff --git a/Changes b/Changes
index 54346a9..3292ba6 100644
--- a/Changes
+++ b/Changes
@@ -1,515 +1,518 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+ - remove bogus work-in-progress signatures-using commit from 6.027;
+ that was a bad release! thanks for the heads-up about it to Gianni
+ "dakkar" Ceccarelli!
6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
4.300039 2013-09-20 06:05:10 Asia/Tokyo
- tweak metafile generator to keep CPAN::Meta validator happy (thanks,
David Golden)
4.300038 2013-09-08 09:18:34 America/New_York
- add horrible hack to avoid generating non-UTF-8 META.yml; seriously,
don't look at the code! Thanks, David Golden, whose code was simple
and probably much, much saner, but didn't cover as many cases as rjbs
wanted to cover.
4.300037 2013-08-28 21:43:36 America/New_York
- update repo and bugtacker URLs
4.300036 2013-08-25 21:41:21 America/New_York
- read CPAN::Uploader config with CPAN::Uploader, to work with new
trial releases supporting encrypted credential (thanks, Mike Doherty)
- improve tester tests (thanks, Dave O'Neill!)
|
rjbs/Dist-Zilla
|
3711ddd9d8aa4994d4977f369deba4347bc0c090
|
v6.027
|
diff --git a/Changes b/Changes
index 377060d..54346a9 100644
--- a/Changes
+++ b/Changes
@@ -1,515 +1,517 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+
+6.027 2022-11-06 17:52:20-05:00 America/New_York
- if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
4.300039 2013-09-20 06:05:10 Asia/Tokyo
- tweak metafile generator to keep CPAN::Meta validator happy (thanks,
David Golden)
4.300038 2013-09-08 09:18:34 America/New_York
- add horrible hack to avoid generating non-UTF-8 META.yml; seriously,
don't look at the code! Thanks, David Golden, whose code was simple
and probably much, much saner, but didn't cover as many cases as rjbs
wanted to cover.
4.300037 2013-08-28 21:43:36 America/New_York
- update repo and bugtacker URLs
4.300036 2013-08-25 21:41:21 America/New_York
- read CPAN::Uploader config with CPAN::Uploader, to work with new
trial releases supporting encrypted credential (thanks, Mike Doherty)
- improve tester tests (thanks, Dave O'Neill!)
- use Class::Load instead of Class::MOP
|
rjbs/Dist-Zilla
|
80f31b93731f94acf7f3c0efd0d7c51a83a2d22d
|
DZIL_COLOR should override auto-detection
|
diff --git a/Changes b/Changes
index fd6044d..377060d 100644
--- a/Changes
+++ b/Changes
@@ -1,515 +1,516 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+ - if DZIL_COLOR is set to 0, override auto-detection
6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
4.300039 2013-09-20 06:05:10 Asia/Tokyo
- tweak metafile generator to keep CPAN::Meta validator happy (thanks,
David Golden)
4.300038 2013-09-08 09:18:34 America/New_York
- add horrible hack to avoid generating non-UTF-8 META.yml; seriously,
don't look at the code! Thanks, David Golden, whose code was simple
and probably much, much saner, but didn't cover as many cases as rjbs
wanted to cover.
4.300037 2013-08-28 21:43:36 America/New_York
- update repo and bugtacker URLs
4.300036 2013-08-25 21:41:21 America/New_York
- read CPAN::Uploader config with CPAN::Uploader, to work with new
trial releases supporting encrypted credential (thanks, Mike Doherty)
- improve tester tests (thanks, Dave O'Neill!)
- use Class::Load instead of Class::MOP
- better error messages when a bundle can't be loaded by @Filter
diff --git a/lib/Dist/Zilla/Chrome/Term.pm b/lib/Dist/Zilla/Chrome/Term.pm
index a6dac15..578115b 100644
--- a/lib/Dist/Zilla/Chrome/Term.pm
+++ b/lib/Dist/Zilla/Chrome/Term.pm
@@ -1,204 +1,206 @@
package Dist::Zilla::Chrome::Term;
# ABSTRACT: chrome used for terminal-based interaction
use Moose;
use Dist::Zilla::Pragmas;
use Digest::MD5 qw(md5);
use Dist::Zilla::Types qw(OneZero);
use Encode ();
use Log::Dispatchouli 1.102220;
use namespace::autoclean;
=head1 OVERVIEW
This class provides a L<Dist::Zilla::Chrome> implementation for use in a
terminal environment. It's the default chrome used by L<Dist::Zilla::App>.
=cut
sub _str_color {
my ($str) = @_;
state %color_for;
# I know, I know, this is ludicrous, but guess what? It's my Sunday and I
# can spend it how I want.
state $max = ($ENV{COLORTERM}//'') eq 'truecolor' ? 255 : 5;
state $min = $max == 255 ? 384 : 5;
state $inc = $max == 255 ? 16 : 1;
state $fmt = $max == 255 ? 'r%ug%ub%u' : 'rgb%u%u%u';
return $color_for{$str} //= do {
my @rgb = map { $_ % $max } unpack 'CCC', md5($str);
my $i = ($rgb[0] + $rgb[1] + $rgb[2]) % 3;
while (1) {
last if $rgb[0] + $rgb[1] + $rgb[2] >= $min;
my $next = $i++ % 3;
$rgb[$next] = abs($max - $rgb[$next]);
}
sprintf $fmt, @rgb;
}
}
has logger => (
is => 'ro',
isa => 'Log::Dispatchouli',
init_arg => undef,
writer => '_set_logger',
lazy => 1,
builder => '_build_logger',
);
sub _build_logger {
my $self = shift;
my $enc = $self->term_enc;
if ($enc && Encode::resolve_alias($enc)) {
my $layer = sprintf(":encoding(%s)", $enc);
binmode( STDOUT, $layer );
binmode( STDERR, $layer );
}
my $logger = Log::Dispatchouli->new({
ident => 'Dist::Zilla',
to_stdout => 1,
log_pid => 0,
to_self => ($ENV{DZIL_TESTING} ? 1 : 0),
quiet_fatal => 'stdout',
});
- if (-t *STDOUT || $ENV{DZIL_COLOR}) {
+ my $use_color = $ENV{DZIL_COLOR} // -t *STDOUT;
+
+ if ($use_color) {
my $stdout = $logger->{dispatcher}->output('stdout');
$stdout->add_callback(sub {
require Term::ANSIColor;
my $message = {@_}->{message};
return $message unless $message =~ s/\A\[([^\]]+)] //;
my $prefix = $1;
return sprintf "[%s] %s",
Term::ANSIColor::colored([ _str_color($prefix) ], $prefix),
$message;
});
}
return $logger;
}
has term_ui => (
is => 'ro',
isa => 'Object',
lazy => 1,
default => sub {
require Term::ReadLine;
require Term::UI;
Term::ReadLine->new('dzil')
},
);
has term_enc => (
is => 'ro',
lazy => 1,
default => sub {
require Term::Encoding;
return Term::Encoding::get_encoding();
},
);
sub prompt_str {
my ($self, $prompt, $arg) = @_;
$arg ||= {};
my $default = $arg->{default};
my $check = $arg->{check};
require Encode;
my $term_enc = $self->term_enc;
my $encode = $term_enc
? sub { Encode::encode($term_enc, shift, Encode::FB_CROAK()) }
: sub { shift };
my $decode = $term_enc
? sub { Encode::decode($term_enc, shift, Encode::FB_CROAK()) }
: sub { shift };
if ($arg->{noecho}) {
require Term::ReadKey;
Term::ReadKey::ReadMode('noecho');
}
my $input_bytes = $self->term_ui->get_reply(
prompt => $encode->($prompt),
allow => $check || sub { length $_[0] },
(defined $default
? (default => $encode->($default))
: ()
),
);
if ($arg->{noecho}) {
Term::ReadKey::ReadMode('normal');
# The \n ending user input disappears under noecho; this ensures
# the next output ends up on the next line.
print "\n";
}
my $input = $decode->($input_bytes);
chomp $input;
return $input;
}
sub prompt_yn {
my ($self, $prompt, $arg) = @_;
$arg ||= {};
my $default = $arg->{default};
if (! $self->_isa_tty) {
if (defined $default) {
return OneZero->coerce($default);
}
$self->logger->log_fatal(
"want interactive input, but terminal doesn't appear interactive"
);
}
my $input = $self->term_ui->ask_yn(
prompt => $prompt,
(defined $default ? (default => OneZero->coerce($default)) : ()),
);
return $input;
}
sub _isa_tty {
my $isa_tty = -t STDIN && (-t STDOUT || !(-f STDOUT || -c STDOUT));
return $isa_tty;
}
sub prompt_any_key {
my ($self, $prompt) = @_;
$prompt ||= 'press any key to continue';
my $isa_tty = $self->_isa_tty;
if ($isa_tty) {
local $| = 1;
print $prompt;
require Term::ReadKey;
Term::ReadKey::ReadMode('cbreak');
Term::ReadKey::ReadKey(0);
Term::ReadKey::ReadMode('normal');
print "\n";
}
}
with 'Dist::Zilla::Role::Chrome';
__PACKAGE__->meta->make_immutable;
1;
|
rjbs/Dist-Zilla
|
2a15d1cda845b766e099a604007bbe921e9bb819
|
v6.025
|
diff --git a/Changes b/Changes
index e5ad7fc..fd6044d 100644
--- a/Changes
+++ b/Changes
@@ -1,515 +1,517 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+
+6.025 2022-05-28 11:55:35-04:00 America/New_York
- eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
4.300039 2013-09-20 06:05:10 Asia/Tokyo
- tweak metafile generator to keep CPAN::Meta validator happy (thanks,
David Golden)
4.300038 2013-09-08 09:18:34 America/New_York
- add horrible hack to avoid generating non-UTF-8 META.yml; seriously,
don't look at the code! Thanks, David Golden, whose code was simple
and probably much, much saner, but didn't cover as many cases as rjbs
wanted to cover.
4.300037 2013-08-28 21:43:36 America/New_York
- update repo and bugtacker URLs
4.300036 2013-08-25 21:41:21 America/New_York
- read CPAN::Uploader config with CPAN::Uploader, to work with new
trial releases supporting encrypted credential (thanks, Mike Doherty)
- improve tester tests (thanks, Dave O'Neill!)
- use Class::Load instead of Class::MOP
- better error messages when a bundle can't be loaded by @Filter
- make dynamic_config distmeta sticky; once one plugin sets it, it
|
rjbs/Dist-Zilla
|
abbca4a4fa04c526757574c1fd981f0349f7760d
|
Dist::Zilla::Path: eliminate use of $;-joined hash key
|
diff --git a/Changes b/Changes
index aa341f7..e5ad7fc 100644
--- a/Changes
+++ b/Changes
@@ -1,515 +1,516 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+ - eliminate use of multidimensional array emulation
6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
4.300039 2013-09-20 06:05:10 Asia/Tokyo
- tweak metafile generator to keep CPAN::Meta validator happy (thanks,
David Golden)
4.300038 2013-09-08 09:18:34 America/New_York
- add horrible hack to avoid generating non-UTF-8 META.yml; seriously,
don't look at the code! Thanks, David Golden, whose code was simple
and probably much, much saner, but didn't cover as many cases as rjbs
wanted to cover.
4.300037 2013-08-28 21:43:36 America/New_York
- update repo and bugtacker URLs
4.300036 2013-08-25 21:41:21 America/New_York
- read CPAN::Uploader config with CPAN::Uploader, to work with new
trial releases supporting encrypted credential (thanks, Mike Doherty)
- improve tester tests (thanks, Dave O'Neill!)
- use Class::Load instead of Class::MOP
- better error messages when a bundle can't be loaded by @Filter
- make dynamic_config distmeta sticky; once one plugin sets it, it
stays stuck
diff --git a/lib/Dist/Zilla/Path.pm b/lib/Dist/Zilla/Path.pm
index f54d604..6579813 100644
--- a/lib/Dist/Zilla/Path.pm
+++ b/lib/Dist/Zilla/Path.pm
@@ -1,57 +1,59 @@
package Dist::Zilla::Path;
# ABSTRACT: a helper to get Path::Tiny objects
# BEGIN BOILERPLATE
use v5.20.0;
use warnings;
use utf8;
no feature 'switch';
use experimental qw(postderef postderef_qq); # This experiment gets mainlined.
# END BOILERPLATE
use parent 'Path::Tiny';
use Path::Tiny 0.052 qw(); # issue 427
use Scalar::Util qw( blessed );
use Sub::Exporter -setup => {
exports => [ qw( path ) ],
groups => { default => [ qw( path ) ] },
};
use namespace::autoclean -except => 'import';
sub path {
my ($thing, @rest) = @_;
if (@rest == 0 && blessed $thing) {
return $thing if $thing->isa(__PACKAGE__);
return bless(Path::Tiny::path("$thing"), __PACKAGE__)
if $thing->isa('Path::Class::Entity') || $thing->isa('Path::Tiny');
}
return bless(Path::Tiny::path($thing, @rest), __PACKAGE__);
}
my %warned;
sub file {
my ($self, @file) = @_;
my ($package, $pmfile, $line) = caller;
- unless ($warned{ $pmfile, $line }++) {
+
+ my $key = join qq{\0}, $pmfile, $line;
+ unless ($warned{ $key }++) {
Carp::carp("->file called on a Dist::Zilla::Path object; this will cease to work in Dist::Zilla v7; downstream code should be updated to use Path::Tiny API, not Path::Class");
}
require Path::Class;
Path::Class::dir($self)->file(@file);
}
sub subdir {
my ($self, @subdir) = @_;
Carp::carp("->subdir called on a Dist::Zilla::Path object; this will cease to work in Dist::Zilla v7; downstream code should be updated to use Path::Tiny API, not Path::Class");
require Path::Class;
Path::Class::dir($self)->subdir(@subdir);
}
1;
|
rjbs/Dist-Zilla
|
fe7256f6283b9efd6966f5fb475d4c34757f7216
|
v6.024
|
diff --git a/Changes b/Changes
index 176d410..aa341f7 100644
--- a/Changes
+++ b/Changes
@@ -1,515 +1,517 @@
Revision history for {{$dist->name}}
{{$NEXT}}
+
+6.024 2021-08-01 15:38:44-04:00 America/New_York
- pass the dist name to Software::License as the program name
(thanks, Van de Bugger!)
- create the ArchiveBuilder role for building the archive file
(thanks, Graham Ollis!)
6.023 2021-07-06 21:37:37-04:00 America/New_York
- tweak the autoprereqs tests to avoid failing when List::MoreUtils
(which DZ does not actually need) is not installed)
6.022 2021-06-27 21:36:53-04:00 America/New_York
- remove dependency on Class::Load, which is not used
- bump prereq on PPI to 1.222, which is now used in PkgVersion
(thanks, Dan Book and Sven Kirmess)
6.021 2021-06-27 21:31:21-04:00 America/New_York
- [ broken release, don't bother ]
6.020 2021-06-14 12:16:09-04:00 America/New_York
- The log colorization code was trying to use 24-bit color even when
the installed Term::ANSIColor couldn't support it. This has been
fixed by requiring Term::ANSIColor v5. Thanks, Robert Rothenberg,
Michael McClimon, and Matthew Horsfall.
6.019 2021-06-13 08:39:14-04:00 America/New_York
- When using "use_package" in PkgVersion, do not eradicate the entire
block of "package NAME BLOCK" syntax! Wow, what a bug...
6.018 2021-04-03 21:07:54-04:00 America/New_York (TRIAL RELEASE)
- require perl v5.20.0, now seven years old
- add Test::CleanNamespaces, clean all namespaces
- add the same boilerplate of version/pragma/features to every module
- colorize logger prefix when running in a terminal
6.017 2020-11-02 19:30:21-05:00 America/New_York
- replace broken 6.016, released from a confused git repo
6.016 2020-11-02 19:27:18-05:00 America/New_York (TRIAL RELEASE)
- the test generated by [MetaTests] is now an author test, not a
release test (thanks, Karen Etheridge)
- UploadToCPAN will now retry (thanks, PERLANCAR)
- some bug fixes for msys (thanks, Håkon Hægland)
6.015 2020-05-29 14:30:51-04:00 America/New_York
- add docs for "dzil release -j" (thanks, Jonas B. Nielsen)
- fix support for dist.pl (why??? ð) (thanks, Kent Frederic)
- remove unnecessary check for Pod::Simple being loaded (Dave Lambley)
6.014 2020-03-01 04:26:38-05:00 America/New_York
- some doc improvements by Shlomi Fish
- cope with E<...> in abstracts (thanks, Dave Lambley!)
- Respect jobs number in HARNESS_OPTIONS (thanks, Leon Timmermans!)
- Add --jobs argument to dzil release (thanks, Leon Timmermans!)
- replace uses of File::HomeDir with a simple glob (thanks, Karen
Etheridge!)
- fix interaction of TRIAL comment and BEGIN block in PkgVersion
(thanks, Michael Conrad and Felix Ostmann)
- fix documentation for default NextRelease format (thanks, Dan Book!)
- the build directory is also added to @INC when evaluating 'dzil
authordeps --missing' (thanks, Karen Etheridge!)
- add comments to generated CPANfile saying "don't edit me!"
(thanks Doug Bell)
- tests for [CPANFile] (thanks, Daniel Böhmer)
6.013 2019-04-30 07:35:49-04:00 America/New_York (TRIAL RELEASE)
- when SPDX metadata is available for the chosen license,
x_spdx_expression is added to the dist metadata by default
(thanks, Leon Timmermans!)
6.012 2018-04-21 10:20:21+02:00 Europe/Oslo
- revert addition of Archive::Tar::Wrapper as a mandatory prereq (in
release 6.011).
- require a version of Config::MVP that adds the cwd back to @INC
- record the perl version being used into META file
- tiny fix to help output for "dzil new"
6.011 2018-02-11 12:57:02-05:00 America/New_York
- stashes can now be added in [%Stash] form from a bundle (thanks,
Karen Etheridge)
- use $V env var as an override, when set, in [AutoVersion]
(thanks, Karen Etheridge)
- all remaining uses of Class::Load are replaced with Module::Runtime
(thanks, Karen Etheridge)
6.010 2017-07-10 09:22:16-04:00 America/New_York
- a few documentation improvements (thanks, Chase Whitener, Mary
Ehlers, and Jonas B. Nielsen)
- improve behavior under a noninteractive terminal
- empty file finders should now consistently return []
6.009 2017-03-04 11:16:37-05:00 America/New_York
- update DateTime::TimeZone prereq on Win32 to improve workingness
(thanks, Schwern!)
- add --recommends and --requires and --suggests to listdeps
- improve testing of listdeps (thanks, Mickey Nasriachi!)
- Module::Runtime is now considered 'internal' for the purpose of
carping (thanks, Karen Etheridge!)
- ./tmp is now pruned by PruneCruft (thanks, Karen Etheridge!)
- authordeps now picks up :version for the root section (thanks,
Karen!)
- the config loading of the "perl" config loader is more reliable, but
still please don't use it (thanks, Karen!)
- introducing a new plugin, [GatherFile], to support adding individual
files to the distribution (thanks, Karen!)
6.008 2016-10-05 21:35:23-04:00 America/New_York
- fix the skip message from ExtraTests (thanks, Roy Ivy â
¢!)
- cope with error changes in latest Moose (thanks, Karen Etheridge and
Dave Rolsky)
- always stringify $] in MetaConfig to avoid losing trailing zeroes
through numification (thanks, Karen Etheridge!)
6.007 2016-08-06 14:04:39-04:00 America/New_York
- restrict [MetaYAML] to metaspec v1.4, [MetaJSON] to v2.0+, as other
version combinations are not well-supported by the toolchain
6.006 2016-07-04 10:56:36-04:00 America/New_York
- add some documentation to Dist::Zilla::App::Tester (thanks, Alberto
Simões!)
- optimizations to regex munging (thanks, Olivier Mengué!)
- add x_serialization_backend to META.* files (thanks, Karen
Etheridge!)
- metadata plugins are called before metadata defaults are built
(thanks, Karen Etheridge!)
- don't use ExtraTests plugin, but if you do, its generated test files
are a bit faster when unused
6.005 2016-05-23 08:08:15-04:00 America/New_York
- NextRelease now dies if there's no changelog file found
(thanks, Karen Etheridge)
- Module::Runtime replaces Class::Load (thanks Olivier Mengué)
6.004 2016-05-14 09:14:19-04:00 America/New_York (TRIAL RELEASE)
- stop listing Path::Class as a prereq (thanks, Karen Etheridge)
- update docs on path types (thanks, Graham Ollis)
6.003 2016-04-24 19:23:46+01:00 Europe/London (TRIAL RELEASE)
- leading BOM (FEFF) is stripped on UTF-8 content
- PPI now handles characters, not bytes, fixing non-ASCII
non-comments in your source
6.002 2016-04-23 17:50:26+01:00 Europe/London (TRIAL RELEASE)
- tweaks to Dist::Zilla::Path to keep plugins from v5 era working
6.001 2016-04-23 13:21:56+01:00 Europe/London
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Using a Dist::Zilla::Path like a Path::Class object now issues a
deprecation warning ("this will be removed") once per call site.
6.000 2016-04-23 11:35:28+01:00 Europe/London (TRIAL RELEASE)
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- Path::Class has been excised in favor of Path::Tiny, exposed as
Dist::Zilla::Path; it will still respond to ->subdir and ->file, but
only until Dist::Zilla v7 -- fix your plugins by then!
- The --verbose switch to dzil is now strictly on/off. To set
verbosity on a per-plugin basis, use the -V switch. Unfortunately,
per-plugin verbosity seems to have been broken for some time, anyway.
- The plugins [Prereq] and [AutoPrereq] and [BumpVersion] have been
removed. These were long deprecated. (Don't confuse Prereq, for
example, with the plural Prereqs, which is the correct plugin.)
- [PkgVersion] now supports a use_package argument which will put the
version in the package statement. (Remember that this syntax was
introduced in perl v5.12.0.)
- Dist::Zilla now requires perl v5.14.0. It will still happily build
dists that run on whatever version of perl you like.
5.047 2016-04-23 16:20:13+01:00 Europe/London
- cast things to Path::Class as needed, for now, for v6 backcompat
(don't expect more commits like this)
5.046 2016-04-22 15:50:27+01:00 Europe/London
- avoid using syntax that is called ambiguous on older perls
5.045 2016-04-22 11:37:13+01:00 Europe/London
- add 'relationship' option to AutoPrereqs plugin (Karen Etheridge)
- PrereqScanner role abstracts much of the AutoPrereqs behavior
(thanks, Olivier Mengué!)
- remove duplicates from the results of the :ExecFiles filefinder
- [MakeMaker] now rejects version ranges in prereqs if eumm_version is
not specified to be high enough (7.1101) to guarantee it can be
handled (Karen Etheridge)
- allow comments in an authordep specification with a version
- make FakeReleaser a bit more of a drop-in for UploadToCPAN
(Erik Carlsson)
- make PkgDist preserve blank line after 'package' for PkgVersion
(Chisel Wright)
- add rename option to [GatherDir::Template] (Alastair McGowan-Douglas)
- META.json is now emitted in ASCII (using \u... for non-ASCII
characters) to avoid a bug in older versions of JSON::PP on older
versions of perl
- "dzil build --in ." no longer allows you to blow away your cwd
5.044 2016-04-06 20:32:14-04:00 America/New_York
- require a newer List::Util to avoid a dumb bug caused by relying on
side effects of loading Moose (thanks, Karen Etheridge!)
5.043 2016-01-04 22:54:56-05:00 America/New_York
- dzil test now supports --extended to set EXTENDED_TESTING (thanks,
Philippe Bruhat)
5.042 2015-11-26 09:05:37-05:00 America/New_York
- try to avoid testing errors when the local time zone can't be
determined (https://github.com/rjbs/Dist-Zilla/issues/497)
5.041 2015-10-27 22:07:54-04:00 America/New_York
- add 'static_attribution' attribution to MakeMaker plugin
- fix prereqs for App::Cmd and Config::MVP::Reader::INI
5.040 2015-10-13 11:42:25-04:00 America/New_York
- the distribution tarball name no longer includes -TRIAL if the
version contains an underscore
- [PkgVersion] adds "$VERSION = $VERSION_SANS_UNDERSCORES" when
version contains an underscore
- made the PodCoverageTests and PodSyntaxTests plugins generate author
tests, not release tests. These are tests you want passing on every
commit, not just before a release (Dave Rolsky)
5.039 2015-08-10 09:03:08-04:00 America/New_York
- update required version of MooseX::Role::Parameterized; older
versions work, but can cause a bunch of unwanted warnings
5.038 2015-08-07 22:16:50-04:00 America/New_York
- [License] can be given a filename option to use instead of LICENSE
- dzil listdeps --develop now exists as an alias for dzil listdeps
--author (Karen Etheridge)
- dzil authordeps now lists the Software::License class needed
(thanks, David Zurborg)
- PkgVersion now skips .pod files (thanks, David Golden)
- build_element support added for [ModuleBuild] (thanks, David
Wheeler!)
- new native filefinder :ExtraTestFiles (thanks, Karen Etheridge)
- [AutoPrereqs] now looks for develop prerequisites in xt/ (thanks,
Karen Etheridge)
- new file finder ':PerlExecFiles' (thanks, Karen Etheridge)
- try harder to notice failure to set up build root, especially on
Win32 (thanks, Christian Walde)
- better errors when a global config package isn't available (thanks,
Karen Etheridge)
- added the "ignore" option to [Encoding] (thanks, Yanick Champoux)
- allow ; authordep specifications to contain version ranges (thanks,
Karen Etheridge)
- better error when PAUSE credentials can't be loaded (thanks, David
Golden)
- fix documentation for the LicenseProvider role
- improve errors when PPI failes to parse (thanks, Nick Tonkin)
- sort list of executable files in Makefile.PL, for deterministic
builds (thanks, Karen Etheridge)
- omit configure-requires prerequisites from [MakeMaker]'s fallback
prerequisites (used by older ExtUtils::MakeMaker)
5.037 2015-06-04 21:46:38-04:00 America/New_York
- issue a warning when version ranges are passed through to
ExtUtils::MakeMaker, which cannot parse them and treats them as '0'
https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/215
- added %P formatter code to [NextRelease] for the releaser's PAUSE id
5.036 2015-05-02 11:08:51-04:00 America/New_York
- BUGFIX: detection of trial status via underscore in version was
accidentally lost in v5.035; restored now!
5.035 2015-04-16 15:43:26+02:00 Europe/Berlin
- BREAKING CHANGE: is_trial is now read-only
- release_status is a new Dist::Zilla attribute and
ReleaseStatusProvider plugin role
5.034 2015-03-20 10:57:07-04:00 America/New_York
- require new Config::MVP for better exceptions (that we rely on)
- point to IRC in dist metadata
5.033 2015-03-17 07:45:36-04:00 America/New_York
- NextRelease now bases the new file on disk on the original file on
disk, skipping any munging that happened in between
- improve error message when a plugin can't be loaded
- added "use_begin" option to PkgVersion
5.032 2015-02-21 09:36:00-05:00 America/New_York
- when :version is in plugin config, it's now enforced as soon as it's
seen
- add more documentation about bytes/text files
- PruneCruft also prunes _eumm/* now
5.031 2015-01-08 22:04:30-05:00 America/New_York
- correct a test to avoid testing symlinks on Win32
5.030 2015-01-04 22:31:38-05:00 America/New_York
- fixed [GatherDir]'s handling of symlinks to directories
- [AutoPrereqs] now filters out all namespaces found in contained
modules, not just the one corresponding to the module filename
5.029 2014-12-14 14:44:44-05:00 America/New_York
- fix new error in [PkgVersion] when a module had no package
statements
- further rip out use of JSON.pm
5.028 2014-12-12 19:06:23-05:00 America/New_York
- fix regression in [PkgVersion] that made false-positive
identifications for pre-existing assignments to $VERSION
- try avoid cases in which plugin code directly modifies file list
- switch, tentatively, to JSON::MaybeXS
5.027 2014-12-09 09:30:30-05:00 America/New_York
- fix regression in Plugin->plugin_from_config which started passing a
list of pairs rather than a hashref
5.026 2014-12-08 21:33:55-05:00 America/New_York
- eliminate use of Moose::Autobox
- various small performance optimizations
- add "use_our" option to PkgVersion
5.025 2014-11-10 21:12:14-05:00 America/New_York
- fix file.t failures with perl v5.14 and v5.16's Carp
5.024 2014-11-05 23:08:07-05:00 America/New_York
- add the %Mint stash for minting defaults
- quiet down some low-priority log lines
- teeny tiny optimization by building dist prereqs structure lazily
- avoid ever requiring v0 of ExtUtils::MakeMaker
- fix a module-loading ordering issue in `dzil setup`
5.023 2014-10-30 22:56:42-04:00 America/New_York
- optimizations to loading of heavyweight libraries in cmd line app
- some tests are now skipped on Win32 to avoid filename insanity
- files' added_by data should be more informative
- conflicts with installed code is now detected and/or advertised
5.022 2014-10-27 22:55:53-04:00 America/New_York
- several optimizations to how PPI is used
- handle an empty ABSTRACT better
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge
- create Makefile.PL and Build.PL files earlier, so they're in the file
list "the whole time"
5.021 2014-10-20 22:43:52-04:00 America/New_York
- improve authordeps' ability to cope with version requirements and
non-default plugin names
- a few improvements to help given by "dzil help COMMAND"
- fixes a situation where exclusion-regexp-building in GatherDir
could mangle the given regexps
- now properly merging distmeta fragments together without loss, using
new CPAN::Meta::Merge (Karen Etheridge)
- [PkgVersion] now properly skips over $VERSION assignments in
comments (Karen Etheridge, github #322)
- the building of manpages is supressed in [MakeMaker]-driven builds
- lazily load quite a few more modules
- avoid using user's ~/.dzil even more
- while building dists for testing, don't bother building man pages
- try harder to notice minimum required perl version
- try harder to delete temporarily directory at the end of testing
- don't treat $VERSION assignments in comments as $VERSION assignments
- listdeps now takes --omit-core to skip core modules
- don't try to use terminal encoding on locale-free systems
- suggest the use of PPI::XS
- speed up and debug behavior of GatherDir
5.020 2014-07-28 20:56:25-04:00 America/New_York
- the default required version for ExtUtils::MakeMaker in [MakeMaker]
has been removed
- load DateTime lazily
- the default required version for Module::Build in [ModuleBuild] has
been lowered
5.019 2014-05-20 21:11:47-04:00 America/New_York
- remove a very brief-lived attempt to double-decode
5.018 2014-05-20 21:07:04-04:00 America/New_York
- attempt to return abstract-from-file as a string, rather than
bytes, which can lead to weirdness (github issue #303)
5.017 2014-05-17 08:35:33-04:00 America/New_York
- dotfiles and dot-directories are now included in sharedirs
- ModuleBuild and MakeMake should not re-build if it isn't needed
- authordeps now better understands "perl" dep
- munging of README is delayed to prevent unneeded work and
complication
- MANIFEST is now treated as a binary file
- 'dzil setup' now warns that credentials are stored in the clear
- MakeMaker should include fewer empty and useless hashrefs
- Makefile.old is now pruned as cruft
5.016 2014-05-05 22:27:06-04:00 America/New_York
- hint about [Encoding] plugin in encoding error message (David
Golden)
5.015 2014-03-30 21:55:36-04:00 America/New_York
- make it easier to have multiple PAUSE configs using UploadToCPAN's
pause_cfg_dir option (thanks, David Golden)
5.014 2014-03-16 16:47:07+01:00 Europe/Paris
- Added 'jobs' argument for 'dzil test' for parallel testing (thanks,
David Golden!)
- add default_jobs attribute to TestRunner role
- fix the behavior of 'dzil add' with more than one file
(thanks, Leon Timmermans!)
5.013 2014-02-08 17:08:16-05:00 America/New_York
- META.json is now a UTF-8 file, rather than ASCII
- document the use of filefinders in [PkgVersion], and remove
filtering out of .t, .pod files; do skip non-text files, though
- always load modules in "extra tests" like pod-coverage.t
- PruneCruft also prunes ./fatlib
- avoid being tricked by statements in __END__ section when looking for
variable assignments
- if "dzil install" fails due to exception, it is now propagated
- provide a better error when terminal encoding can't be determined
5.012 2014-01-15 09:58:00-05:00 America/New_York
- when handling a multi-line abstract, fold the lines on whitespace;
previously, the newlines had been left in, which caused downstream
warnings
5.011 2014-01-12 16:09:29-05:00 America/New_York
- ->VERSION is again defined in the tester forms of Builder and Minter
- remove a small obsolete code path from PkgVersion
5.010 2014-01-11 22:06:04-05:00 America/New_York
- stop sharing a reference to cached PPI docs, which led to spooky
action at a distance
- PkgVersion no longer surrounds the new $VERSION assignment with a
bare block
- if there's a blank line after the package statement (and any number
of comment-only lines), PkgVersion will use that for a $VERSION
assignment, rather than insert a new line; this can be made mandatory
with die_on_line_insertion
5.009 2014-01-07 20:21:17-05:00 America/New_York
- include time offset by default in NextRelease
- always pass PPI octets, not text
5.008 2013-12-27 21:57:02 America/New_York
- fix utterly broken `dzil run`
5.007 2013-12-27 20:50:45-05:00 America/New_York
- add the ability to say "dzil run --no-build" to run a command without
building inside the dist dir
(in other words, no `perl Makefile.PL && make`)
- Archive::Tar::Wrapper added as a recommended prereq
- fix :ShareFiles (thanks, Christopher J. Madsen and Karen Etheridge)
- new :AllFiles and :NoFiles filefinders (thanks, Karen Etheridge)
- most files generated by dzil plugins now self-identify with comments
5.006 2013-11-06 09:21:12 America/New_York
- add ->is_bytes to files; shortcut for ->encoding eq 'bytes'
(thanks, David Golden)
- AutoPrereqs will not try scanning binary files (thanks, David Golden)
5.005 2013-11-02 16:32:04 America/New_York
- add --keep-build-dir to "dzil test" and "dzil install"
5.004 2013-11-02 09:59:18 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- stable release of all the v5 changes below; READ THEM!
- by default, NextRelease now adds a trial release marker on trial
releases
- dzil setup will not echo password during setup
5.003 2013-10-30 08:02:59 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- add "dzil --version" support (thanks, Upasana Shukla)
- fix boneheaded mistake that broke listdeps in 5.002 (thanks, Karen
Etheridge)
5.002 2013-10-29 10:35:54 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- perform encoding steps during listdeps
5.001 2013-10-23 17:40:09 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- typo fixes (thanks, David Steinbrunner)
5.000 2013-10-20 08:10:02 America/New_York
[THIS RELEASE MIGHT BREAK YOUR BUILD]
- all files now have content, encoded_content, and encoding attributes
- the Encoding plugin and EncodingProvider role have been added to
allow you to set the encoding on files; the default is UTF-8
- config.ini is assumed to be in UTF-8
- Data::Section sections are assumed to be UTF-8
- the Term chrome should encode input and output
4.300039 2013-09-20 06:05:10 Asia/Tokyo
- tweak metafile generator to keep CPAN::Meta validator happy (thanks,
David Golden)
4.300038 2013-09-08 09:18:34 America/New_York
- add horrible hack to avoid generating non-UTF-8 META.yml; seriously,
don't look at the code! Thanks, David Golden, whose code was simple
and probably much, much saner, but didn't cover as many cases as rjbs
wanted to cover.
4.300037 2013-08-28 21:43:36 America/New_York
- update repo and bugtacker URLs
4.300036 2013-08-25 21:41:21 America/New_York
- read CPAN::Uploader config with CPAN::Uploader, to work with new
trial releases supporting encrypted credential (thanks, Mike Doherty)
- improve tester tests (thanks, Dave O'Neill!)
- use Class::Load instead of Class::MOP
- better error messages when a bundle can't be loaded by @Filter
- make dynamic_config distmeta sticky; once one plugin sets it, it
stays stuck
- add a die_on_existing_version option to PkgVersion
|
rjbs/Dist-Zilla
|
31b480b77a2dfe54459405b6365b16cb3daf866d
|
ignore DS_Store files (sigh)
|
diff --git a/.gitignore b/.gitignore
index 67ce244..a311ede 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,15 +1,16 @@
Dist-Zilla-*
.build
tmp
*.patch
+.DS_Store
.gitnxtver_cache
# avoid temp and backup files
*~
*#
*.bak
*.old
*.rej
*.swp
*.tmp
|
rjbs/Dist-Zilla
|
a7417d5417d875c202ae8bff3558c7367976d7e5
|
add a opengraph card because why not
|
diff --git a/misc/DZ.graffle b/misc/DZ.graffle
new file mode 100644
index 0000000..ed0e034
Binary files /dev/null and b/misc/DZ.graffle differ
|
rjbs/Dist-Zilla
|
acae2ee4a76092a08582b2e89ac09393dc9abaf3
|
require new Software::License for ->program
|
diff --git a/lib/Dist/Zilla.pm b/lib/Dist/Zilla.pm
index 694a6ee..4bf33b1 100644
--- a/lib/Dist/Zilla.pm
+++ b/lib/Dist/Zilla.pm
@@ -1,538 +1,538 @@
package Dist::Zilla;
# ABSTRACT: distribution builder; installer not included!
use Moose 0.92; # role composition fixes
with 'Dist::Zilla::Role::ConfigDumper';
# BEGIN BOILERPLATE
use v5.20.0;
use warnings;
use utf8;
no feature 'switch';
use experimental qw(postderef postderef_qq); # This experiment gets mainlined.
# END BOILERPLATE
# This comment has fünÌnÌÿ characters.
use MooseX::Types::Moose qw(ArrayRef Bool HashRef Object Str);
use MooseX::Types::Perl qw(DistName LaxVersionStr);
use Moose::Util::TypeConstraints;
use Dist::Zilla::Types qw(Path License ReleaseStatus);
use Log::Dispatchouli 1.100712; # proxy_loggers, quiet_fatal
use Dist::Zilla::Path;
use List::Util 1.33 qw(first none);
-use Software::License 0.103014; # spdx_expression()
+use Software::License 0.104001; # ->program
use String::RewritePrefix;
use Try::Tiny;
use Dist::Zilla::Prereqs;
use Dist::Zilla::File::OnDisk;
use Dist::Zilla::Role::Plugin;
use Dist::Zilla::Util;
use Module::Runtime 'require_module';
use namespace::autoclean;
=head1 DESCRIPTION
Dist::Zilla builds distributions of code to be uploaded to the CPAN. In this
respect, it is like L<ExtUtils::MakeMaker>, L<Module::Build>, or
L<Module::Install>. Unlike those tools, however, it is not also a system for
installing code that has been downloaded from the CPAN. Since it's only run by
authors, and is meant to be run on a repository checkout rather than on
published, released code, it can do much more than those tools, and is free to
make much more ludicrous demands in terms of prerequisites.
If you have access to the web, you can learn more and find an interactive
tutorial at B<L<dzil.org|http://dzil.org/>>. If not, try
L<Dist::Zilla::Tutorial>.
=cut
has chrome => (
is => 'rw',
isa => role_type('Dist::Zilla::Role::Chrome'),
required => 1,
);
=attr name
The name attribute (which is required) gives the name of the distribution to be
built. This is usually the name of the distribution's main module, with the
double colons (C<::>) replaced with dashes. For example: C<Dist-Zilla>.
=cut
has name => (
is => 'ro',
isa => DistName,
lazy => 1,
builder => '_build_name',
);
=attr version
This is the version of the distribution to be created.
=cut
has _version_override => (
isa => LaxVersionStr,
is => 'ro' ,
init_arg => 'version',
);
# XXX: *clearly* this needs to be really much smarter -- rjbs, 2008-06-01
has version => (
is => 'rw',
isa => LaxVersionStr,
lazy => 1,
init_arg => undef,
builder => '_build_version',
);
sub _build_name {
my ($self) = @_;
my $name;
for my $plugin (@{ $self->plugins_with(-NameProvider) }) {
next unless defined(my $this_name = $plugin->provide_name);
$self->log_fatal('attempted to set name twice') if defined $name;
$name = $this_name;
}
$self->log_fatal('no name was ever set') unless defined $name;
$name;
}
sub _build_version {
my ($self) = @_;
my $version = $self->_version_override;
for my $plugin (@{ $self->plugins_with(-VersionProvider) }) {
next unless defined(my $this_version = $plugin->provide_version);
$self->log_fatal('attempted to set version twice') if defined $version;
$version = $this_version;
}
$self->log_fatal('no version was ever set') unless defined $version;
$version;
}
=attr release_status
This attribute sets the release status to one of the
L<CPAN::META::Spec|https://metacpan.org/pod/CPAN::Meta::Spec#release_status>
values: 'stable', 'testing' or 'unstable'.
If the C<$ENV{RELEASE_STATUS}> environment variable exists, its value will
be used as the release status.
For backwards compatibility, if C<$ENV{RELEASE_STATUS}> does not exist and
the C<$ENV{TRIAL}> variable is true, the release status will be 'testing'.
Otherwise, the release status will be set from a
L<ReleaseStatusProvider|Dist::Zilla::Role::ReleaseStatusProvider>, if one
has been configured.
For backwards compatibility, setting C<is_trial> true in F<dist.ini> is
equivalent to using a C<ReleaseStatusProvider>. If C<is_trial> is false,
it has no effect.
Only B<one> C<ReleaseStatusProvider> may be used.
If no providers are used, the release status defaults to 'stable' unless there
is an "_" character in the version, in which case, it defaults to 'testing'.
=cut
# release status must be lazy, after files are gathered
has release_status => (
is => 'ro',
isa => ReleaseStatus,
lazy => 1,
builder => '_build_release_status',
);
sub _build_release_status {
my ($self) = @_;
# environment variables override completely
return $self->_release_status_from_env if $self->_release_status_from_env;
# other ways of setting status must not conflict
my $status;
# dist.ini is equivalent to a release provider if is_trial is true.
# If false, though, we want other providers to run or fall back to
# the version
$status = 'testing' if $self->_override_is_trial;
for my $plugin (@{ $self->plugins_with(-ReleaseStatusProvider) }) {
next unless defined(my $this_status = $plugin->provide_release_status);
$self->log_fatal('attempted to set release status twice')
if defined $status;
$status = $this_status;
}
return $status || ( $self->version =~ /_/ ? 'testing' : 'stable' );
}
# captures environment variables early during Zilla object construction
has _release_status_from_env => (
is => 'ro',
isa => Str,
builder => '_build_release_status_from_env',
);
sub _build_release_status_from_env {
my ($self) = @_;
return $ENV{RELEASE_STATUS} if $ENV{RELEASE_STATUS};
return $ENV{TRIAL} ? 'testing' : '';
}
=attr abstract
This is a one-line summary of the distribution. If none is given, one will be
looked for in the L</main_module> of the dist.
=cut
has abstract => (
is => 'rw',
isa => 'Str',
lazy => 1,
default => sub {
my ($self) = @_;
unless ($self->main_module) {
die "no abstract given and no main_module found; make sure your main module is in ./lib\n";
}
my $file = $self->main_module;
$self->log_debug("extracting distribution abstract from " . $file->name);
my $abstract = Dist::Zilla::Util->abstract_from_file($file);
if (!defined($abstract)) {
my $filename = $file->name;
die "Unable to extract an abstract from $filename. Please add the following comment to the file with your abstract:
# ABSTRACT: turns baubles into trinkets
";
}
return $abstract;
}
);
=attr main_module
This is the module where Dist::Zilla might look for various defaults, like
the distribution abstract. By default, it's derived from the distribution
name. If your distribution is Foo-Bar, and F<lib/Foo/Bar.pm> exists,
that's the main_module. Otherwise, it's the shortest-named module in the
distribution. This may change!
You can override the default by specifying the file path explicitly,
ie:
main_module = lib/Foo/Bar.pm
=cut
has _main_module_override => (
isa => 'Str',
is => 'ro' ,
init_arg => 'main_module',
predicate => '_has_main_module_override',
);
has main_module => (
is => 'ro',
isa => 'Dist::Zilla::Role::File',
lazy => 1,
init_arg => undef,
default => sub {
my ($self) = @_;
my $file;
my $guess;
if ( $self->_has_main_module_override ) {
$file = first { $_->name eq $self->_main_module_override }
@{ $self->files };
} else {
# We're having to guess
$guess = $self->name =~ s{-}{/}gr;
$guess = "lib/$guess.pm";
$file = (first { $_->name eq $guess } @{ $self->files })
|| (sort { length $a->name <=> length $b->name }
grep { $_->name =~ m{\.pm\z} and $_->name =~ m{\Alib/} }
@{ $self->files })[0];
$self->log("guessing dist's main_module is " . ($file ? $file->name : $guess));
}
if (not $file) {
my @errorlines;
push @errorlines, "Unable to find main_module in the distribution";
if ($self->_has_main_module_override) {
push @errorlines, "'main_module' was specified in dist.ini but the file '" . $self->_main_module_override . "' is not to be found in our dist. ( Did you add it? )";
} else {
push @errorlines,"We tried to guess '$guess' but no file like that existed";
}
if (not @{ $self->files }) {
push @errorlines, "Upon further inspection we didn't find any files in your dist, did you add any?";
} elsif ( none { $_->name =~ m{^lib/.+\.pm\z} } @{ $self->files } ){
push @errorlines, "We didn't find any .pm files in your dist, this is probably a problem.";
}
push @errorlines,"Cannot continue without a main_module";
$self->log_fatal( join qq{\n}, @errorlines );
}
$self->log_debug("dist's main_module is " . $file->name);
return $file;
},
);
=attr license
This is the L<Software::License|Software::License> object for this dist's
license and copyright.
It will be created automatically, if possible, with the
C<copyright_holder> and C<copyright_year> attributes. If necessary, it will
try to guess the license from the POD of the dist's main module.
A better option is to set the C<license> name in the dist's config to something
understandable, like C<Perl_5>.
=cut
has license => (
is => 'ro',
isa => License,
lazy => 1,
init_arg => 'license_obj',
predicate => '_has_license',
builder => '_build_license',
handles => {
copyright_holder => 'holder',
copyright_year => 'year',
},
);
sub _build_license {
my ($self) = @_;
my $license_class = $self->_license_class;
my $copyright_holder = $self->_copyright_holder;
my $copyright_year = $self->_copyright_year;
my $provided_license;
for my $plugin (@{ $self->plugins_with(-LicenseProvider) }) {
my $this_license = $plugin->provide_license({
copyright_holder => $copyright_holder,
copyright_year => $copyright_year,
});
next unless defined $this_license;
$self->log_fatal('attempted to set license twice')
if defined $provided_license;
$provided_license = $this_license;
}
return $provided_license if defined $provided_license;
if ($license_class) {
$license_class = String::RewritePrefix->rewrite(
{
'=' => '',
'' => 'Software::License::'
},
$license_class,
);
} else {
require Software::LicenseUtils;
my @guess = Software::LicenseUtils->guess_license_from_pod(
$self->main_module->content
);
if (@guess != 1) {
$self->log_fatal(
"no license data in config, no %Rights stash,",
"couldn't make a good guess at license from Pod; giving up. ",
"Perhaps you need to set up a global config file (dzil setup)?"
);
}
my $filename = $self->main_module->name;
$license_class = $guess[0];
$self->log("based on POD in $filename, guessing license is $guess[0]");
}
unless (eval { require_module($license_class) }) {
$self->log_fatal(
"could not load class $license_class for license " . $self->_license_class
);
}
my $license = $license_class->new({
holder => $self->_copyright_holder,
year => $self->_copyright_year,
program => $self->name,
});
$self->_clear_license_class;
$self->_clear_copyright_holder;
$self->_clear_copyright_year;
return $license;
}
has _license_class => (
is => 'ro',
isa => 'Maybe[Str]',
lazy => 1,
init_arg => 'license',
clearer => '_clear_license_class',
default => sub {
my $stash = $_[0]->stash_named('%Rights');
$stash && return $stash->license_class;
return;
}
);
has _copyright_holder => (
is => 'ro',
isa => 'Maybe[Str]',
lazy => 1,
init_arg => 'copyright_holder',
clearer => '_clear_copyright_holder',
default => sub {
return unless my $stash = $_[0]->stash_named('%Rights');
$stash && return $stash->copyright_holder;
return;
}
);
has _copyright_year => (
is => 'ro',
isa => 'Str',
lazy => 1,
init_arg => 'copyright_year',
clearer => '_clear_copyright_year',
default => sub {
# Oh man. This is a terrible idea! I mean, what if by the code gets run
# around like Dec 31, 23:59:59.9 and by the time the default gets called
# it's the next year but the default was already set up? Oh man. That
# could ruin lives! I guess we could make this a sub to defer the guess,
# but think of the performance hit! I guess we'll have to suffer through
# this until we can optimize the code to not take .1s to run, right? --
# rjbs, 2008-06-13
my $stash = $_[0]->stash_named('%Rights');
my $year = $stash && $stash->copyright_year;
return( $year // (localtime)[5] + 1900 );
}
);
=attr authors
This is an arrayref of author strings, like this:
[
'Ricardo Signes <[email protected]>',
'X. Ample, Jr <[email protected]>',
]
This is likely to change at some point in the near future.
=cut
has authors => (
is => 'ro',
isa => ArrayRef[Str],
lazy => 1,
default => sub {
my ($self) = @_;
if (my $stash = $self->stash_named('%User')) {
return $stash->authors;
}
my $author = try { $self->copyright_holder };
return [ $author ] if length $author;
$self->log_fatal(
"No %User stash and no copyright holder;",
"can't determine dist author; configure author or a %User section",
);
},
);
=attr files
This is an arrayref of objects implementing L<Dist::Zilla::Role::File> that
will, if left in this arrayref, be built into the dist.
Non-core code should avoid altering this arrayref, but sometimes there is not
other way to change the list of files. In the future, the representation used
for storing files B<will be changed>.
=cut
has files => (
is => 'ro',
isa => ArrayRef[ role_type('Dist::Zilla::Role::File') ],
lazy => 1,
init_arg => undef,
default => sub { [] },
);
sub prune_file {
my ($self, $file) = @_;
my @files = @{ $self->files };
for my $i (0 .. $#files) {
next unless $file == $files[ $i ];
splice @{ $self->files }, $i, 1;
return;
}
return;
}
=attr root
This is the root directory of the dist, as a L<Path::Tiny>. It will
nearly always be the current working directory in which C<dzil> was run.
=cut
has root => (
is => 'ro',
isa => Path,
coerce => 1,
required => 1,
);
=attr is_trial
This attribute tells us whether or not the dist will be a trial release,
i.e. whether it has C<release_status> 'testing' or 'unstable'.
|
rjbs/Dist-Zilla
|
06451638761b96fd6b63896eb18b531f29ae0594
|
Distribution name is passed to Software::License constructor as "program" argument.
|
diff --git a/lib/Dist/Zilla.pm b/lib/Dist/Zilla.pm
index 238ba5a..694a6ee 100644
--- a/lib/Dist/Zilla.pm
+++ b/lib/Dist/Zilla.pm
@@ -1,894 +1,895 @@
package Dist::Zilla;
# ABSTRACT: distribution builder; installer not included!
use Moose 0.92; # role composition fixes
with 'Dist::Zilla::Role::ConfigDumper';
# BEGIN BOILERPLATE
use v5.20.0;
use warnings;
use utf8;
no feature 'switch';
use experimental qw(postderef postderef_qq); # This experiment gets mainlined.
# END BOILERPLATE
# This comment has fünÌnÌÿ characters.
use MooseX::Types::Moose qw(ArrayRef Bool HashRef Object Str);
use MooseX::Types::Perl qw(DistName LaxVersionStr);
use Moose::Util::TypeConstraints;
use Dist::Zilla::Types qw(Path License ReleaseStatus);
use Log::Dispatchouli 1.100712; # proxy_loggers, quiet_fatal
use Dist::Zilla::Path;
use List::Util 1.33 qw(first none);
use Software::License 0.103014; # spdx_expression()
use String::RewritePrefix;
use Try::Tiny;
use Dist::Zilla::Prereqs;
use Dist::Zilla::File::OnDisk;
use Dist::Zilla::Role::Plugin;
use Dist::Zilla::Util;
use Module::Runtime 'require_module';
use namespace::autoclean;
=head1 DESCRIPTION
Dist::Zilla builds distributions of code to be uploaded to the CPAN. In this
respect, it is like L<ExtUtils::MakeMaker>, L<Module::Build>, or
L<Module::Install>. Unlike those tools, however, it is not also a system for
installing code that has been downloaded from the CPAN. Since it's only run by
authors, and is meant to be run on a repository checkout rather than on
published, released code, it can do much more than those tools, and is free to
make much more ludicrous demands in terms of prerequisites.
If you have access to the web, you can learn more and find an interactive
tutorial at B<L<dzil.org|http://dzil.org/>>. If not, try
L<Dist::Zilla::Tutorial>.
=cut
has chrome => (
is => 'rw',
isa => role_type('Dist::Zilla::Role::Chrome'),
required => 1,
);
=attr name
The name attribute (which is required) gives the name of the distribution to be
built. This is usually the name of the distribution's main module, with the
double colons (C<::>) replaced with dashes. For example: C<Dist-Zilla>.
=cut
has name => (
is => 'ro',
isa => DistName,
lazy => 1,
builder => '_build_name',
);
=attr version
This is the version of the distribution to be created.
=cut
has _version_override => (
isa => LaxVersionStr,
is => 'ro' ,
init_arg => 'version',
);
# XXX: *clearly* this needs to be really much smarter -- rjbs, 2008-06-01
has version => (
is => 'rw',
isa => LaxVersionStr,
lazy => 1,
init_arg => undef,
builder => '_build_version',
);
sub _build_name {
my ($self) = @_;
my $name;
for my $plugin (@{ $self->plugins_with(-NameProvider) }) {
next unless defined(my $this_name = $plugin->provide_name);
$self->log_fatal('attempted to set name twice') if defined $name;
$name = $this_name;
}
$self->log_fatal('no name was ever set') unless defined $name;
$name;
}
sub _build_version {
my ($self) = @_;
my $version = $self->_version_override;
for my $plugin (@{ $self->plugins_with(-VersionProvider) }) {
next unless defined(my $this_version = $plugin->provide_version);
$self->log_fatal('attempted to set version twice') if defined $version;
$version = $this_version;
}
$self->log_fatal('no version was ever set') unless defined $version;
$version;
}
=attr release_status
This attribute sets the release status to one of the
L<CPAN::META::Spec|https://metacpan.org/pod/CPAN::Meta::Spec#release_status>
values: 'stable', 'testing' or 'unstable'.
If the C<$ENV{RELEASE_STATUS}> environment variable exists, its value will
be used as the release status.
For backwards compatibility, if C<$ENV{RELEASE_STATUS}> does not exist and
the C<$ENV{TRIAL}> variable is true, the release status will be 'testing'.
Otherwise, the release status will be set from a
L<ReleaseStatusProvider|Dist::Zilla::Role::ReleaseStatusProvider>, if one
has been configured.
For backwards compatibility, setting C<is_trial> true in F<dist.ini> is
equivalent to using a C<ReleaseStatusProvider>. If C<is_trial> is false,
it has no effect.
Only B<one> C<ReleaseStatusProvider> may be used.
If no providers are used, the release status defaults to 'stable' unless there
is an "_" character in the version, in which case, it defaults to 'testing'.
=cut
# release status must be lazy, after files are gathered
has release_status => (
is => 'ro',
isa => ReleaseStatus,
lazy => 1,
builder => '_build_release_status',
);
sub _build_release_status {
my ($self) = @_;
# environment variables override completely
return $self->_release_status_from_env if $self->_release_status_from_env;
# other ways of setting status must not conflict
my $status;
# dist.ini is equivalent to a release provider if is_trial is true.
# If false, though, we want other providers to run or fall back to
# the version
$status = 'testing' if $self->_override_is_trial;
for my $plugin (@{ $self->plugins_with(-ReleaseStatusProvider) }) {
next unless defined(my $this_status = $plugin->provide_release_status);
$self->log_fatal('attempted to set release status twice')
if defined $status;
$status = $this_status;
}
return $status || ( $self->version =~ /_/ ? 'testing' : 'stable' );
}
# captures environment variables early during Zilla object construction
has _release_status_from_env => (
is => 'ro',
isa => Str,
builder => '_build_release_status_from_env',
);
sub _build_release_status_from_env {
my ($self) = @_;
return $ENV{RELEASE_STATUS} if $ENV{RELEASE_STATUS};
return $ENV{TRIAL} ? 'testing' : '';
}
=attr abstract
This is a one-line summary of the distribution. If none is given, one will be
looked for in the L</main_module> of the dist.
=cut
has abstract => (
is => 'rw',
isa => 'Str',
lazy => 1,
default => sub {
my ($self) = @_;
unless ($self->main_module) {
die "no abstract given and no main_module found; make sure your main module is in ./lib\n";
}
my $file = $self->main_module;
$self->log_debug("extracting distribution abstract from " . $file->name);
my $abstract = Dist::Zilla::Util->abstract_from_file($file);
if (!defined($abstract)) {
my $filename = $file->name;
die "Unable to extract an abstract from $filename. Please add the following comment to the file with your abstract:
# ABSTRACT: turns baubles into trinkets
";
}
return $abstract;
}
);
=attr main_module
This is the module where Dist::Zilla might look for various defaults, like
the distribution abstract. By default, it's derived from the distribution
name. If your distribution is Foo-Bar, and F<lib/Foo/Bar.pm> exists,
that's the main_module. Otherwise, it's the shortest-named module in the
distribution. This may change!
You can override the default by specifying the file path explicitly,
ie:
main_module = lib/Foo/Bar.pm
=cut
has _main_module_override => (
isa => 'Str',
is => 'ro' ,
init_arg => 'main_module',
predicate => '_has_main_module_override',
);
has main_module => (
is => 'ro',
isa => 'Dist::Zilla::Role::File',
lazy => 1,
init_arg => undef,
default => sub {
my ($self) = @_;
my $file;
my $guess;
if ( $self->_has_main_module_override ) {
$file = first { $_->name eq $self->_main_module_override }
@{ $self->files };
} else {
# We're having to guess
$guess = $self->name =~ s{-}{/}gr;
$guess = "lib/$guess.pm";
$file = (first { $_->name eq $guess } @{ $self->files })
|| (sort { length $a->name <=> length $b->name }
grep { $_->name =~ m{\.pm\z} and $_->name =~ m{\Alib/} }
@{ $self->files })[0];
$self->log("guessing dist's main_module is " . ($file ? $file->name : $guess));
}
if (not $file) {
my @errorlines;
push @errorlines, "Unable to find main_module in the distribution";
if ($self->_has_main_module_override) {
push @errorlines, "'main_module' was specified in dist.ini but the file '" . $self->_main_module_override . "' is not to be found in our dist. ( Did you add it? )";
} else {
push @errorlines,"We tried to guess '$guess' but no file like that existed";
}
if (not @{ $self->files }) {
push @errorlines, "Upon further inspection we didn't find any files in your dist, did you add any?";
} elsif ( none { $_->name =~ m{^lib/.+\.pm\z} } @{ $self->files } ){
push @errorlines, "We didn't find any .pm files in your dist, this is probably a problem.";
}
push @errorlines,"Cannot continue without a main_module";
$self->log_fatal( join qq{\n}, @errorlines );
}
$self->log_debug("dist's main_module is " . $file->name);
return $file;
},
);
=attr license
This is the L<Software::License|Software::License> object for this dist's
license and copyright.
It will be created automatically, if possible, with the
C<copyright_holder> and C<copyright_year> attributes. If necessary, it will
try to guess the license from the POD of the dist's main module.
A better option is to set the C<license> name in the dist's config to something
understandable, like C<Perl_5>.
=cut
has license => (
is => 'ro',
isa => License,
lazy => 1,
init_arg => 'license_obj',
predicate => '_has_license',
builder => '_build_license',
handles => {
copyright_holder => 'holder',
copyright_year => 'year',
},
);
sub _build_license {
my ($self) = @_;
my $license_class = $self->_license_class;
my $copyright_holder = $self->_copyright_holder;
my $copyright_year = $self->_copyright_year;
my $provided_license;
for my $plugin (@{ $self->plugins_with(-LicenseProvider) }) {
my $this_license = $plugin->provide_license({
copyright_holder => $copyright_holder,
copyright_year => $copyright_year,
});
next unless defined $this_license;
$self->log_fatal('attempted to set license twice')
if defined $provided_license;
$provided_license = $this_license;
}
return $provided_license if defined $provided_license;
if ($license_class) {
$license_class = String::RewritePrefix->rewrite(
{
'=' => '',
'' => 'Software::License::'
},
$license_class,
);
} else {
require Software::LicenseUtils;
my @guess = Software::LicenseUtils->guess_license_from_pod(
$self->main_module->content
);
if (@guess != 1) {
$self->log_fatal(
"no license data in config, no %Rights stash,",
"couldn't make a good guess at license from Pod; giving up. ",
"Perhaps you need to set up a global config file (dzil setup)?"
);
}
my $filename = $self->main_module->name;
$license_class = $guess[0];
$self->log("based on POD in $filename, guessing license is $guess[0]");
}
unless (eval { require_module($license_class) }) {
$self->log_fatal(
"could not load class $license_class for license " . $self->_license_class
);
}
my $license = $license_class->new({
- holder => $self->_copyright_holder,
- year => $self->_copyright_year,
+ holder => $self->_copyright_holder,
+ year => $self->_copyright_year,
+ program => $self->name,
});
$self->_clear_license_class;
$self->_clear_copyright_holder;
$self->_clear_copyright_year;
return $license;
}
has _license_class => (
is => 'ro',
isa => 'Maybe[Str]',
lazy => 1,
init_arg => 'license',
clearer => '_clear_license_class',
default => sub {
my $stash = $_[0]->stash_named('%Rights');
$stash && return $stash->license_class;
return;
}
);
has _copyright_holder => (
is => 'ro',
isa => 'Maybe[Str]',
lazy => 1,
init_arg => 'copyright_holder',
clearer => '_clear_copyright_holder',
default => sub {
return unless my $stash = $_[0]->stash_named('%Rights');
$stash && return $stash->copyright_holder;
return;
}
);
has _copyright_year => (
is => 'ro',
isa => 'Str',
lazy => 1,
init_arg => 'copyright_year',
clearer => '_clear_copyright_year',
default => sub {
# Oh man. This is a terrible idea! I mean, what if by the code gets run
# around like Dec 31, 23:59:59.9 and by the time the default gets called
# it's the next year but the default was already set up? Oh man. That
# could ruin lives! I guess we could make this a sub to defer the guess,
# but think of the performance hit! I guess we'll have to suffer through
# this until we can optimize the code to not take .1s to run, right? --
# rjbs, 2008-06-13
my $stash = $_[0]->stash_named('%Rights');
my $year = $stash && $stash->copyright_year;
return( $year // (localtime)[5] + 1900 );
}
);
=attr authors
This is an arrayref of author strings, like this:
[
'Ricardo Signes <[email protected]>',
'X. Ample, Jr <[email protected]>',
]
This is likely to change at some point in the near future.
=cut
has authors => (
is => 'ro',
isa => ArrayRef[Str],
lazy => 1,
default => sub {
my ($self) = @_;
if (my $stash = $self->stash_named('%User')) {
return $stash->authors;
}
my $author = try { $self->copyright_holder };
return [ $author ] if length $author;
$self->log_fatal(
"No %User stash and no copyright holder;",
"can't determine dist author; configure author or a %User section",
);
},
);
=attr files
This is an arrayref of objects implementing L<Dist::Zilla::Role::File> that
will, if left in this arrayref, be built into the dist.
Non-core code should avoid altering this arrayref, but sometimes there is not
other way to change the list of files. In the future, the representation used
for storing files B<will be changed>.
=cut
has files => (
is => 'ro',
isa => ArrayRef[ role_type('Dist::Zilla::Role::File') ],
lazy => 1,
init_arg => undef,
default => sub { [] },
);
sub prune_file {
my ($self, $file) = @_;
my @files = @{ $self->files };
for my $i (0 .. $#files) {
next unless $file == $files[ $i ];
splice @{ $self->files }, $i, 1;
return;
}
return;
}
=attr root
This is the root directory of the dist, as a L<Path::Tiny>. It will
nearly always be the current working directory in which C<dzil> was run.
=cut
has root => (
is => 'ro',
isa => Path,
coerce => 1,
required => 1,
);
=attr is_trial
This attribute tells us whether or not the dist will be a trial release,
i.e. whether it has C<release_status> 'testing' or 'unstable'.
Do not set this directly, it will be derived from C<release_status>.
=cut
has is_trial => (
is => 'ro',
isa => Bool,
init_arg => undef,
lazy => 1,
builder => '_build_is_trial',
);
has _override_is_trial => (
is => 'ro',
isa => Bool,
init_arg => 'is_trial',
default => 0,
);
sub _build_is_trial {
my ($self) = @_;
return $self->release_status =~ /\A(?:testing|unstable)\z/ ? 1 : 0;
}
=attr plugins
This is an arrayref of plugins that have been plugged into this Dist::Zilla
object.
Non-core code B<must not> alter this arrayref. Public access to this attribute
B<may go away> in the future.
=cut
has plugins => (
is => 'ro',
isa => 'ArrayRef[Dist::Zilla::Role::Plugin]',
init_arg => undef,
default => sub { [ ] },
);
=attr distmeta
This is a hashref containing the metadata about this distribution that will be
stored in META.yml or META.json. You should not alter the metadata in this
hash; use a MetaProvider plugin instead.
=cut
has distmeta => (
is => 'ro',
isa => 'HashRef',
init_arg => undef,
lazy => 1,
builder => '_build_distmeta',
);
sub _build_distmeta {
my ($self) = @_;
require CPAN::Meta::Merge;
my $meta_merge = CPAN::Meta::Merge->new(default_version => 2);
my $meta = {};
for (@{ $self->plugins_with(-MetaProvider) }) {
$meta = $meta_merge->merge($meta, $_->metadata);
}
my %meta_main = (
'meta-spec' => {
version => 2,
url => 'https://metacpan.org/pod/CPAN::Meta::Spec',
},
name => $self->name,
version => $self->version,
abstract => $self->abstract,
author => $self->authors,
license => [ $self->license->meta2_name ],
release_status => $self->release_status,
dynamic_config => 0, # problematic, I bet -- rjbs, 2010-06-04
generated_by => $self->_metadata_generator_id
. ' version '
. ($self->VERSION // '(undef)'),
x_generated_by_perl => "$^V", # v5.24.0
);
if (my $spdx = $self->license->spdx_expression) {
$meta_main{x_spdx_expression} = $spdx;
}
$meta = $meta_merge->merge($meta, \%meta_main);
return $meta;
}
sub _metadata_generator_id { 'Dist::Zilla' }
=attr prereqs
This is a L<Dist::Zilla::Prereqs> object, which is a thin layer atop
L<CPAN::Meta::Prereqs>, and describes the distribution's prerequisites.
=method register_prereqs
Allows registration of prerequisites; delegates to
L<Dist::Zilla::Prereqs/register_prereqs> via our L</prereqs> attribute.
=cut
has prereqs => (
is => 'ro',
isa => 'Dist::Zilla::Prereqs',
init_arg => undef,
lazy => 1,
default => sub { Dist::Zilla::Prereqs->new },
handles => [ qw(register_prereqs) ],
);
=method plugin_named
my $plugin = $zilla->plugin_named( $plugin_name );
=cut
sub plugin_named {
my ($self, $name) = @_;
my $plugin = first { $_->plugin_name eq $name } @{ $self->plugins };
return $plugin if $plugin;
return;
}
=method plugins_with
my $roles = $zilla->plugins_with( -SomeRole );
This method returns an arrayref containing all the Dist::Zilla object's plugins
that perform the named role. If the given role name begins with a dash, the
dash is replaced with "Dist::Zilla::Role::"
=cut
sub plugins_with {
my ($self, $role) = @_;
$role =~ s/^-/Dist::Zilla::Role::/;
my $plugins = [ grep { $_->does($role) } @{ $self->plugins } ];
return $plugins;
}
=method find_files
my $files = $zilla->find_files( $finder_name );
This method will look for a
L<FileFinder|Dist::Zilla::Role::FileFinder>-performing plugin with the given
name and return the result of calling C<find_files> on it. If no plugin can be
found, an exception will be raised.
=cut
sub find_files {
my ($self, $finder_name) = @_;
$self->log_fatal("no plugin named $finder_name found")
unless my $plugin = $self->plugin_named($finder_name);
$self->log_fatal("plugin $finder_name is not a FileFinder")
unless $plugin->does('Dist::Zilla::Role::FileFinder');
$plugin->find_files;
}
sub _check_dupe_files {
my ($self) = @_;
my %files_named;
my @dupes;
for my $file (@{ $self->files }) {
my $filename = $file->name;
if (my $seen = $files_named{ $filename }) {
push @{ $seen }, $file;
push @dupes, $filename if @{ $seen } == 2;
} else {
$files_named{ $filename } = [ $file ];
}
}
return unless @dupes;
for my $name (@dupes) {
$self->log("attempt to add $name multiple times; added by: "
. join('; ', map { $_->added_by } @{ $files_named{ $name } })
);
}
Carp::croak("aborting; duplicate files would be produced");
}
sub _write_out_file {
my ($self, $file, $build_root) = @_;
# Okay, this is a bit much, until we have ->debug. -- rjbs, 2008-06-13
# $self->log("writing out " . $file->name);
my $file_path = path($file->name);
my $to_dir = path($build_root)->child( $file_path->parent );
my $to = $to_dir->child( $file_path->basename );
$to_dir->mkpath unless -e $to_dir;
die "not a directory: $to_dir" unless -d $to_dir;
Carp::croak("attempted to write $to multiple times") if -e $to;
path("$to")->spew_raw( $file->encoded_content );
chmod $file->mode, "$to" or die "couldn't chmod $to: $!";
}
=attr logger
This attribute stores a L<Log::Dispatchouli::Proxy> object, used to log
messages. By default, a proxy to the dist's L<Chrome|Dist::Zilla::Role::Chrome> is
taken.
The following methods are delegated from the Dist::Zilla object to the logger:
=for :list
* log
* log_debug
* log_fatal
=cut
has logger => (
is => 'ro',
isa => 'Log::Dispatchouli::Proxy', # could be duck typed, I guess
lazy => 1,
handles => [ qw(log log_debug log_fatal) ],
default => sub {
$_[0]->chrome->logger->proxy({ proxy_prefix => '[DZ] ' })
},
);
around dump_config => sub {
my ($orig, $self) = @_;
my $config = $self->$orig;
$config->{is_trial} = $self->is_trial;
return $config;
};
has _local_stashes => (
is => 'ro',
isa => HashRef[ Object ],
lazy => 1,
default => sub { {} },
);
has _global_stashes => (
is => 'ro',
isa => HashRef[ Object ],
lazy => 1,
default => sub { {} },
);
=method stash_named
my $stash = $zilla->stash_named( $name );
This method will return the stash with the given name, or undef if none exists.
It looks for a local stash (for this dist) first, then falls back to a global
stash (from the user's global configuration).
=cut
sub stash_named {
my ($self, $name) = @_;
return $self->_local_stashes->{ $name } if $self->_local_stashes->{$name};
return $self->_global_stashes->{ $name };
}
__PACKAGE__->meta->make_immutable;
1;
=head1 STABILITY PROMISE
None.
I will try not to break things within any major release. Minor releases are
not extensively tested before release. In major releases, anything goes,
although I will try to publish a complete list of known breaking changes in any
major release.
If Dist::Zilla was a tool, it would have yellow and black stripes and there
would be no L<UL
certification|https://en.wikipedia.org/wiki/UL_(safety_organization)> on it.
It is nasty, brutish, and large.
=head1 SUPPORT
There are usually people on C<irc.perl.org> in C<#distzilla>, even if they're
idling.
The L<Dist::Zilla website|http://dzil.org/> has several valuable resources for
learning to use Dist::Zilla.
There is a mailing list to discuss Dist::Zilla. You can L<join the
list|http://www.listbox.com/subscribe/?list_id=139292> or L<browse the
archives|http://listbox.com/member/archive/139292>.
=head1 SEE ALSO
=over 4
=item *
In the Dist::Zilla distribution:
=over 4
=item *
Plugin bundles:
L<@Basic|Dist::Zilla::PluginBundle::Basic>,
L<@Filter|Dist::Zilla::PluginBundle::Filter>.
=item *
Major plugins:
L<GatherDir|Dist::Zilla::Plugin::GatherDir>,
L<Prereqs|Dist::Zilla::Plugin::Prereqs>,
L<AutoPrereqs|Dist::Zilla::Plugin::AutoPrereqs>,
L<MetaYAML|Dist::Zilla::Plugin::MetaYAML>,
L<MetaJSON|Dist::Zilla::Plugin::MetaJSON>,
...
=back
=item *
On the CPAN:
=over 4
=item *
Search for plugins: L<https://metacpan.org/search?q=Dist::Zilla::Plugin::>
=item *
Search for plugin bundles: L<https://metacpan.org/search?q=Dist::Zilla::PluginBundle::>
=back
=back
|
rdno/pardus-network-manager-gtk
|
936fd7fe849962d15391ec583f88c4c271ac96f6
|
added asma addon
|
diff --git a/asma/__init__.py b/asma/__init__.py
new file mode 100644
index 0000000..836e3e8
--- /dev/null
+++ b/asma/__init__.py
@@ -0,0 +1,2 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
diff --git a/asma/addons/__init__.py b/asma/addons/__init__.py
new file mode 100644
index 0000000..836e3e8
--- /dev/null
+++ b/asma/addons/__init__.py
@@ -0,0 +1,2 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
diff --git a/asma/addons/network_manager.py b/asma/addons/network_manager.py
new file mode 100644
index 0000000..77f980d
--- /dev/null
+++ b/asma/addons/network_manager.py
@@ -0,0 +1,29 @@
+# -*- coding: utf-8 -*-
+#
+# Rıdvan Ãrsvuran (C) 2010
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+from asma.addon import AsmaAddon
+from network_manager_gtk import NetworkManager
+from network_manager_gtk.translation import _
+class NetworkManagerAddon(AsmaAddon):
+ """Network Manager Asma addon"""
+ def __init__(self):
+ """init the variables"""
+ super(NetworkManagerAddon, self).__init__()
+ self._uuid = "62e6a90b-52cc-4cba-86eb-56894fa7d893"
+ self._icon_name = "applications-internet"
+ self._label = _("Network Manager")
+ self._widget = NetworkManager
diff --git a/setup.py b/setup.py
index 9907905..1efaa96 100755
--- a/setup.py
+++ b/setup.py
@@ -1,13 +1,13 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name="pardus-network-manager-gtk",
- version="0.1.1",
- packages = ["network_manager_gtk"],
+ version="0.1.2",
+ packages = ["network_manager_gtk", "asma.addons"],
scripts = ["network-manager-gtk.py"],
description= "Pardus Network Manager's gtk port",
author="Rıdvan Ãrsvuran",
author_email="[email protected]"
)
|
rdno/pardus-network-manager-gtk
|
5394fa940e904f0aecf14745ebd25a1d94338da1
|
refactored code
|
diff --git a/.gitignore b/.gitignore
index 6ee580a..f2c6508 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,7 @@
*~
*.pyc
TAGS
.directory
#*
*.glade.h
+*.mo
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..768b2a6
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,19 @@
+NAME=network_manager_gtk
+LANGS= "en" "tr"
+
+all:
+ echo "make (tags | clean | pot | mo)"
+tags:
+ etags *.py $(NAME)/*.py
+clean:
+ find . -name "*~" -exec rm {} \;
+ find . -name "*.pyc" -exec rm {} \;
+ find . -name "\#*" -exec rm {} \;
+pot:
+ xgettext --keyword=_ -f "po/POTFILES.in" --output="po/$(NAME).pot"
+mo:
+ @for lang in $(LANGS);\
+ do \
+ mkdir -p locale/$$lang/LC_MESSAGES; \
+ msgfmt --output-file=locale/$$lang/LC_MESSAGES/$(NAME).mo po/$$lang.po; \
+ done
diff --git a/make.py b/make.py
deleted file mode 100755
index 35219c4..0000000
--- a/make.py
+++ /dev/null
@@ -1,44 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-#
-# Rıdvan Ãrsvuran (C) 2009
-import os
-import sys
-LANGS = ["en", "tr"]
-def mo():
- for lang in LANGS:
- os.system("mkdir -p locale/%s/LC_MESSAGES" % lang)
- os.system("msgfmt --output-file=locale/%s/LC_MESSAGES/network_manager_gtk.mo po/%s.po" % (lang, lang))
-def pot():
- #glade_extract("main.glade")
- #glade_extract("edit.glade")
- xgettext_cmd = "xgettext --keyword=_ --keyword=N_"
- os.system("%s -f %s --output=%s" % (xgettext_cmd,
- "po/POTFILES.in",
- "po/network_manager_gtk.pot"))
-def tags():
- os.system("etags network-manager-gtk.py network_manager_gtk/*.py")
-
-def glade_extract(file):
- """intltool-extract glade file to .h
- Arguments:
- - `file`:glade file name
- """
- os.system("intltool-extract --type=gettext/glade ui/"+file)
-
-def help():
- print """make pot : makes .pot
-make mo : makes .mo files
-make tags: makes TAGS (emacs) file"""
-if __name__ == '__main__':
- if len(sys.argv) > 1:
- if sys.argv[1] == "mo":
- mo()
- elif sys.argv[1] == "pot":
- pot()
- elif sys.argv[1] == "tags":
- tags()
- else:
- help()
- else:
- help()
diff --git a/network-manager-gtk.py b/network-manager-gtk.py
index 2fe57b4..f797646 100755
--- a/network-manager-gtk.py
+++ b/network-manager-gtk.py
@@ -1,53 +1,52 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
-
#
-# Rıdvan Ãrsvuran (C) 2009
+# Rıdvan Ãrsvuran (C) 2009, 2010
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
-import os
-
import pygtk
pygtk.require('2.0')
import gtk
-from network_manager_gtk.backend import NetworkIface
-
-from network_manager_gtk.windows import MainWindow
+from network_manager_gtk import NetworkManager
+from network_manager_gtk.translation import _
+from network_manager_gtk.windows import BaseWindow
-
-class Base(object):
+class MainWindow(BaseWindow):
+ """Standalone window for network_manager_gtk"""
def __init__(self):
- self._dbusMainLoop()
- self.iface = NetworkIface()
- self.window = MainWindow(self.iface)
-
- def _dbusMainLoop(self):
- from dbus.mainloop.glib import DBusGMainLoop
- DBusGMainLoop(set_as_default = True)
+ """init"""
+ self.manager = NetworkManager()
+ BaseWindow.__init__(self, None)
+ def _set_style(self):
+ self.set_title(_("Network Manager"))
+ self.set_default_size(483, 300)
+ def _create_ui(self):
+ self.add(self.manager)
+ def _listen_signals(self):
+ self.connect("destroy", gtk.main_quit)
+ def run(self, args):
+ """Runs the program with args
- def run(self, argv=None):
- """Runs the program
Arguments:
- `argv`: sys.argv
"""
- self.window.show_all()
+ self.show_all()
gtk.main()
if __name__ == "__main__":
import sys
- app = Base()
- app.run(sys.argv)
+ MainWindow().run(sys.argv)
diff --git a/network_manager_gtk/__init__.py b/network_manager_gtk/__init__.py
index c89582d..f30d576 100644
--- a/network_manager_gtk/__init__.py
+++ b/network_manager_gtk/__init__.py
@@ -1 +1,137 @@
-__all__ = ["translation", "widgets"]
+# -*- coding: utf-8 -*-
+"""NetworkManager gtk Main Module
+
+NetworkManager - Network Manager gtk's main widget
+
+"""
+#
+# Rıdvan Ãrsvuran (C) 2009, 2010
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+
+__all__ = ["backend", "translation", "widgets", "windows",
+ "NetworkManager"]
+
+import gtk
+import gobject
+
+from dbus.mainloop.glib import DBusGMainLoop
+
+from network_manager_gtk.backend import NetworkIface
+from network_manager_gtk.translation import _
+from network_manager_gtk.widgets import ProfilesHolder
+from network_manager_gtk.windows import EditWindow
+from network_manager_gtk.windows import NewConnectionWindow
+
+class NetworkManager(gtk.VBox):
+ """Network Manager gtk's main widget"""
+ def __init__(self):
+ """init"""
+ gtk.VBox.__init__(self, homogeneous=False, spacing=5)
+ self._dbus_loop()
+ self.iface = NetworkIface()
+ self.get_state = lambda p,c:self.iface.info(p,c)[u"state"]
+ self._create_ui()
+ self._listen_signals()
+ def _dbus_loop(self):
+ #runs dbus main loop
+ DBusGMainLoop(set_as_default=True)
+ def _create_ui(self):
+ #creates ui elements
+ self._new_btn = gtk.Button(_('New Connection'))
+ self.pack_start(self._new_btn, expand=False)
+
+ self._holder = ProfilesHolder()
+ self._holder.set_connection_signal(self._connection_callback)
+ self.pack_start(self._holder, expand=True, fill=True)
+ self._get_profiles()
+ def _connection_callback(self, widget, data):
+ """listens ConnectionWidget's signals
+
+ Arguments:
+ - `widget`: widget
+ - `data`: {'action':(toggle | edit | delete)
+ 'package':package_name,
+ 'connection':connection_name}
+ """
+ action = data["action"]
+ if action == "toggle":
+ self.iface.toggle(data["package"],
+ data["connection"])
+ elif action == "edit":
+ EditWindow(self.iface,
+ data["package"],
+ data["connection"]).show()
+ else:
+ m = _("Do you want to delete the connection '%s' ?") % \
+ data['connection']
+ dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING,
+ buttons=gtk.BUTTONS_YES_NO,
+ message_format=m)
+ response = dialog.run()
+ if response == gtk.RESPONSE_YES:
+ try:
+ self.iface.deleteConnection(data['package'],
+ data['connection'])
+ except Exception, e:
+ print "Exception:",e
+ dialog.destroy()
+ def _listen_signals(self):
+ """listen some signals"""
+ self._new_btn.connect("clicked", self.new_profile)
+ self.iface.listen(self._listen_comar)
+ def new_profile(self, widget):
+ #TODO: classic mode support
+ self.classic = False
+ if self.classic:
+ device = self.iface.devices("wireless_tools").keys()[0]
+ EditWindow(self.iface,"wireless_tools", "new",
+ device_id=device)
+ else:
+ NewConnectionWindow(self.iface).show()
+ def _listen_comar(self, package, signal, args):
+ """comar listener
+
+ Arguments:
+ - `package`: package
+ - `signal`: signal type
+ - `args`: arguments
+ """
+ args = map(lambda x: unicode(x), list(args))
+ if signal == "stateChanged":
+ self._holder.update_profile(package,
+ args[0],
+ args[1:])
+ elif signal == "deviceChanged":
+ print "TODO:Listen comar signal deviceChanged "
+ elif signal == "connectionChanged":
+ if args[0] == u"changed":
+ pass#Nothing to do ?
+ elif args[0] == u"added":
+ self._holder.add_profile(package,
+ args[1],
+ self.get_state(package,
+ args[1]))
+ elif args[0] == u"deleted":
+ self._holder.remove_profile(package,
+ args[1])
+ def _get_profiles(self):
+ """get profiles from iface"""
+ for package in self.iface.packages():
+ for connection in self.iface.connections(package):
+ state = self.get_state(package, connection)
+ self._holder.add_profile(package,
+ connection,
+ state)
diff --git a/network_manager_gtk/translation.py b/network_manager_gtk/translation.py
index 6e275d1..3bc4c75 100644
--- a/network_manager_gtk/translation.py
+++ b/network_manager_gtk/translation.py
@@ -1,32 +1,37 @@
-#!/usr/bin/python
# -*- coding: utf-8 -*-
+"""includes network_manager_gtk's translation related stuff
+_ - trans.ugettext (ex: _('string to translate'))
+bind_glade_domain - bind domain for glade translation
+
+"""
#
-# Rıdvan Ãrsvuran (C) 2009
+# Rıdvan Ãrsvuran (C) 2009, 2010
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import gettext
APP_NAME="network_manager_gtk"
LOCALE_DIR= "/usr/share/locale"
+fallback = False
try:
- trans = gettext.translation(APP_NAME, LOCALE_DIR, fallback=False)
+ trans = gettext.translation(APP_NAME, LOCALE_DIR, fallback=fallback)
except IOError: #dev mode (no install mode)
- trans = gettext.translation(APP_NAME, "locale", fallback=False)
+ trans = gettext.translation(APP_NAME, "locale", fallback=fallback)
_ = trans.ugettext
def bind_glade_domain():
from gtk import glade
glade.bindtextdomain(APP_NAME, LOCALE_DIR)
glade.textdomain(APP_NAME)
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index 24337e6..88b1311 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,800 +1,798 @@
-#!/usr/bin/python
# -*- coding: utf-8 -*-
-
+"""includes Network Manager gtk's widgets
+
+ConnectionWidget - A special widget contains connection related stuff
+ProfilesHolder - Holds Profile List
+WifiItemHolder - holder for wifi connections (for EditWindow)
+NewWifiConnectionItem - new wifi connection item
+ (for NewConnectionWindow)
+NewEthernetConnectionItem - new ethernet connection item
+ (for NewConnectionWindow)
+EditWindowFrame - Base Edit Window Frame
+ProfileFrame - Edit Window > Profile Frame
+NetworkFrame - Edit Window > Network Settings Frame
+NameServerFrame - Edit Window > Name Server Frame
+WirelessFrame - Edit Settings Window > WirelessFrame
+
+"""
#
-# Rıdvan Ãrsvuran (C) 2009
+# Rıdvan Ãrsvuran (C) 2009, 2010
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
- """A special widget contains connection related stuff
- """
+ """A special widget contains connection related stuff"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
self._create_ui()
def _create_ui(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.set_mode(self._state.split(' '))
def set_mode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- `args`: [state, detail]
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
self._info.set_markup(states[args[0]]+':'+
'<span color="green">'+
args[1] +
'</span>')
def connect_signals(self, callback):
"""connect widgets signals
returns {'action':(toggle | edit | delete)
'package':package_name,
'connection':connection_name}
Arguments:
- `callback`: callback function
"""
self.check_btn.connect("pressed", callback,
{"action":"toggle",
"package":self._package_name,
"connection":self._connection_name})
self.edit_btn.connect("clicked", callback,
{"action":"edit",
"package":self._package_name,
"connection":self._connection_name})
self.delete_btn.connect("clicked", callback,
{"action":"delete",
"package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
class ProfilesHolder(gtk.ScrolledWindow):
- """Holds Profile List
- """
-
+ """Holds Profile List"""
def __init__(self):
- """init
- """
+ """init"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
self._vbox = gtk.VBox(homogeneous=False,
spacing=10)
self.add_with_viewport(self._vbox)
self._profiles = {}
def set_connection_signal(self, callback):
"""sets default callback for ConnectionWidget
"""
self._callback = callback
def add_profile(self, package, connection, state):
"""add profiles to vbox
"""
con_wg = ConnectionWidget(package,
connection,
state)
con_wg.connect_signals(self._callback)
self._vbox.pack_start(con_wg, expand=False, fill=False)
if not self._profiles.has_key(package):
self._profiles[package] = {}
self._profiles[package][connection] = {"state":state,
"widget":con_wg}
self._vbox.show_all()
def update_profile(self, package, connection, state):
"""update connection state
"""
c = self._profiles[package][connection]
c["state"] = state
c["widget"].set_mode(state)
def remove_profile(self, package, connection):
"""remove profile
"""
c = self._profiles[package][connection]
self._vbox.remove(c["widget"])
gobject.type_register(ProfilesHolder)
class WifiItemHolder(gtk.ScrolledWindow):
- """holder for wifi connections
- """
-
+ """holder for wifi connections (for EditWindow)"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
return data
return None
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
if self.get_child():
self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
class NewWifiConnectionItem(gtk.Table):
- """new wifi connection
- """
+ """new wifi connection item (for NewConnectionWindow)"""
def __init__(self,
device_id,
connection,
auth_type):
"""init
Arguments:
- `device_id`: connection device
- `connection`: scanRemote callback dict
example: {'remote':'ESSID Name',
'quality':'60',
'quality_max':'100'
'encryption':'wpa-psk',
...}
- `auth_type`: wpa-psk -> WPA Ortak Anahtar
"""
gtk.Table.__init__(self, rows=3, columns=3)
self._device_id = device_id
self._connection = connection
self._type = auth_type
self._create_ui()
def _create_ui(self):
"""creates UI
"""
frac = float(self._connection['quality'])/ \
float(self._connection['quality_max'])
per = self._connection['quality']
self._quality_bar = gtk.ProgressBar()
self._quality_bar.set_fraction(frac)
self._quality_bar.set_text(_("%d%%") % int(per))
self._name_txt = gtk.Label("")
self._name_txt.set_markup("<span color='blue'>" +
self._connection['remote']
+ "</span>")
self._name_txt.set_alignment(0.0 , 0.5)
self._encrypt_txt = gtk.Label(self._type)
self._encrypt_txt.set_alignment(0.0 , 0.5)
self._connect_btn = gtk.Button(_("Connect"))
self.set_row_spacings(5)
self.set_col_spacings(5)
self.attach(self._quality_bar, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._name_txt, 1, 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._encrypt_txt, 1, 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._connect_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(gtk.HSeparator(), 0, 3, 2, 3,
gtk.FILL, gtk.SHRINK)
def on_connect(self, func):
"""on connect button clicked
Arguments:
- `func`: callback function
"""
self._connect_btn.connect("clicked",
func,
{"connection":self._connection,
"device": self._device_id,
"package": "wireless_tools"})
gobject.type_register(NewWifiConnectionItem)
class NewEthernetConnectionItem(gtk.Table):
- """new ethernet connection ite
- """
-
+ """new ethernet connection item (for NewConnectionWindow)"""
def __init__(self, device_id, device_name):
"""init
Arguments:
- `device_id`: device id
- `device_name`: device name to show user
"""
gtk.Table.__init__(self, rows=3, columns=2)
self._device_id = device_id
self._device_name = device_name
self._create_ui()
def _create_ui(self):
"""creates ui
"""
self._name_lb = gtk.Label("")
self._name_lb.set_markup("<span color='blue'>" +
_("Ethernet")
+ "</span>")
self._name_lb.set_alignment(0.0, 0.5)
self._device_name_lb = gtk.Label(self._device_name)
self._device_name_lb.set_alignment(0.0, 0.5)
self._connect_btn = gtk.Button(_("Connect"))
self.set_row_spacings(5)
self.set_col_spacings(5)
self.attach(self._name_lb, 0, 1, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._device_name_lb, 0, 1, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._connect_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(gtk.HSeparator(), 0, 3, 2, 3,
gtk.FILL, gtk.SHRINK)
def on_connect(self, func):
"""on connect button clicked
Arguments:
- `func`:callback function
"""
self._connect_btn.connect("clicked",
func,
{"connection":"",
"device":self._device_id,
"package":"net_tools"})
class EditWindowFrame(gtk.Frame):
- """Base EditWindowFrame
- """
-
+ """Base EditWindowFrame"""
def __init__(self, data):
"""init
Arguments:
- `data`: iface.info
"""
gtk.Frame.__init__(self)
self._create_ui()
self._listen_signals()
self._insert_data(data)
def _create_ui(self):
"""creates ui elements
"""
pass
def _listen_signals(self):
"""listens some signals
"""
pass
def _insert_data(self, data):
"""inserts data
Arguments:
- `data`:data to insert
"""
pass
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
def get_text_of(self, name):
"""gets text from widget in unicode"""
return unicode(name.get_text())
def collect_data(self, data):
"""collect data from ui and append datas to
given(data) dictionary"""
pass
def _rb_callback(self, widget, data):
"""RadioButton callback
Arguments:
- `widget`: widget
- `data`: callback data
"""
#if custom selected enable them
for i in data["enable"]:
i.set_sensitive(data["is_custom"])
#if custom selected disable them
for j in data["disable"]:
j.set_sensitive(not data["is_custom"])
def set_rb_signal(self, rb_list, custom_rb,
on_custom_enable,
on_custom_disable = []):
"""Sets RadioButton signals
and adjust behaviour
Arguments:
- `rb_list`: RadioButton list
- `custom_rb`: RadioButton labeled Custom
- `on_custom_enable`: List of widgets to enable
if custom selected
- `on_custom_disable`: List of widgets to disable
if custom selected
"""
for i in rb_list:
i.connect("clicked", self._rb_callback,
{"is_custom":i == custom_rb,
"enable":on_custom_enable,
"disable":on_custom_disable})
class ProfileFrame(EditWindowFrame):
- """Edit Window > Profile Frame
- """
+ """Edit Window > Profile Frame"""
def __init__(self, data):
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self.set_label(_("<b>Profile</b>"))
self.get_label_widget().set_use_markup(True)
profile_lb = gtk.Label(_("Profile Name:"))
self._profile_name = gtk.Entry()
self._device_name_lb = gtk.Label("")
self._device_name_lb.set_ellipsize(pango.ELLIPSIZE_MIDDLE)
#structure
hbox = gtk.HBox(homogeneous=False,
spacing=5)
self.add(hbox)
hbox.pack_start(profile_lb, expand=False)
hbox.pack_start(self._profile_name)
hbox.pack_start(self._device_name_lb)
self.show_all()
def _insert_data(self, data):
self.if_available_set(data, "name",
self._profile_name.set_text)
self.if_available_set(data, "device_name",
self._device_name_lb.set_text)
self.device_id = data["device_id"]
#TODO:more than one device support
def collect_data(self, data):
data["name"] = self.get_text_of(self._profile_name)
data["device_id"] = unicode(self.device_id)
class NetworkFrame(EditWindowFrame):
"""Edit Window > Network Settings Frame
"""
def __init__(self, data):
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self.set_label(_("<b>Network Settings</b>"))
self.get_label_widget().set_use_markup(True)
self._dhcp_rb = gtk.RadioButton(label=_("Use DHCP"))
self._custom_rb = gtk.RadioButton(group=self._dhcp_rb,
label=_("Use Manual Settings")
)
self._address_lb = gtk.Label(_("Address:"))
self._address_lb.set_alignment(1.0, 0.5)
self._mask_lb = gtk.Label(_("Network Mask:"))
self._mask_lb.set_alignment(1.0, 0.5)
self._gateway_lb = gtk.Label(_("Default Gateway:"))
self._gateway_lb.set_alignment(1.0, 0.5)
self._address_txt = gtk.Entry()
self._mask_txt = gtk.Entry()
self._gateway_txt = gtk.Entry()
custom = _("Custom")
self._custom_add_cb = gtk.CheckButton(label=custom)
self._custom_gate_cb = gtk.CheckButton(label=custom)
#structure
table = gtk.Table(rows=4, columns=4)
self.add(table)
table.attach(self._dhcp_rb, 0, 1 , 0, 1,
gtk.FILL, gtk.SHRINK)
table.attach(self._custom_rb, 0, 1 , 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._address_lb, 1, 2 , 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._mask_lb, 1, 2 , 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._gateway_lb, 1, 2 , 3, 4,
gtk.FILL, gtk.SHRINK)
table.attach(self._address_txt, 2, 3 , 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
table.attach(self._mask_txt, 2, 3, 2, 3,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
table.attach(self._gateway_txt, 2, 3 , 3, 4,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
table.attach(self._custom_add_cb, 3, 4 , 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._custom_gate_cb, 3, 4 , 3, 4,
gtk.FILL, gtk.SHRINK)
self.show_all()
def _listen_signals(self):
self._rb_list = [self._dhcp_rb, self._custom_rb]
self._on_custom_enable = [self._address_lb,
self._address_txt,
self._mask_lb,
self._mask_txt,
self._gateway_lb,
self._gateway_txt]
self._on_custom_disable = [self._custom_add_cb,
self._custom_gate_cb]
self.set_rb_signal(self._rb_list,
self._custom_rb,
self._on_custom_enable,
self._on_custom_disable)
self._custom_gate_cb.connect("clicked", self._on_custom)
self._custom_add_cb.connect("clicked", self._on_custom)
def _insert_data(self, data):
if data.has_key("net_mode"):
if data["net_mode"] == "auto":
self._dhcp_rb.set_active(True)
self._rb_callback(self._dhcp_rb,
{"is_custom":False,
"enable":self._on_custom_enable,
"disable":self._on_custom_disable})
if self.is_custom(data, "net_gateway"):
self._custom_gate_cb.set_active(True)
if self.is_custom(data, "net_address"):
self._custom_add_cb.set_active(True)
else:
self._custom_rb.set_active(False)
self.if_available_set(data, "net_address",
self._address_txt.set_text)
self.if_available_set(data, "net_mask",
self._mask_txt.set_text)
self.if_available_set(data, "net_gateway",
self._gateway_txt.set_text)
def _on_custom(self, widget):
if widget is self._custom_add_cb:
widgets = self._on_custom_enable[0:4]
else:
widgets = self._on_custom_enable[4:]
for x in widgets:
x.set_sensitive(widget.get_active())
def _rb_callback(self, widget, data):
EditWindowFrame._rb_callback(self, widget, data)
if not data["is_custom"]:
if self._custom_add_cb.get_active():
for x in data["enable"][0:4]:
x.set_sensitive(True)
if self._custom_gate_cb.get_active():
for x in data["enable"][4:]:
x.set_sensitive(True)
def is_custom(self, data, key):
if data.has_key(key):
if data[key] != "":
return True
return False
def collect_data(self, data):
data["net_mode"] = u"auto"
data["net_address"] = u""
data["net_mask"] = u""
data["net_gateway"] = u""
if self._custom_rb.get_active():
data["net_mode"] = u"manual"
if self._address_txt.state == gtk.STATE_NORMAL:
data["net_address"] = self.get_text_of(self._address_txt)
data["net_mask"] = self.get_text_of(self._mask_txt)
if self._gateway_txt.state == gtk.STATE_NORMAL:
data["net_gateway"] = self.get_text_of(self._gateway_txt)
class NameServerFrame(EditWindowFrame):
- """Edit Window > Name Server Frame
- """
-
+ """Edit Window > Name Server Frame"""
def __init__(self, data):
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self.set_label(_("<b>Name Servers</b>"))
self.get_label_widget().set_use_markup(True)
self._default_rb = gtk.RadioButton(label=_("Default"))
self._auto_rb = gtk.RadioButton(group=self._default_rb,
label=_("Automatic"))
self._custom_rb = gtk.RadioButton(group=self._default_rb,
label=_("Custom"))
self._custom_txt = gtk.Entry()
#structure
hbox = gtk.HBox(homogeneous=False,
spacing=5)
self.add(hbox)
hbox.pack_start(self._default_rb, expand=False)
hbox.pack_start(self._auto_rb, expand=False)
hbox.pack_start(self._custom_rb, expand=False)
hbox.pack_start(self._custom_txt, expand=True)
self.show_all()
def _listen_signals(self):
self.set_rb_signal(rb_list=[self._default_rb,
self._auto_rb,
self._custom_rb],
custom_rb=self._custom_rb,
on_custom_enable=[self._custom_txt])
def _insert_data(self, data):
if data.has_key("name_mode"):
self._custom_txt.set_sensitive(False)
if data["name_mode"] == "default":
self._default_rb.set_active(True)
elif data["name_mode"] == "auto":
self._auto_rb.set_active(True)
elif data["name_mode"] == "custom":
self._custom_rb.set_active(True)
self._custom_txt.set_sensitive(True)
self.if_available_set(data, "name_server",
self._custom_txt.set_text)
def collect_data(self, data):
data["name_mode"] = u"default"
data["name_server"] = u""
if self._auto_rb.get_active():
data["name_mode"] = u"auto"
if self._custom_rb.get_active():
data["name_mode"] = u"custom"
data["name_server"] = self.get_text_of(self._custom_txt)
class WirelessFrame(EditWindowFrame):
- """Edit Settings Window > WirelessFrame
- """
-
+ """Edit Settings Window > WirelessFrame"""
def __init__(self, data, iface,
package=None,connection=None,
with_list=True, is_new=False,
select_type="none"):
self.iface = iface
self.package = package
self.connection = connection
self.with_list = with_list
self.is_new = is_new
self.select_type = select_type
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self.set_label(_("<b>Wireless</b>"))
self.get_label_widget().set_use_markup(True)
self._essid_lb = gtk.Label(_("ESSID:"))
self._essid_lb.set_alignment(1.0, 0.5)
self._essid_txt = gtk.Entry()
self._security_lb = gtk.Label(_("Security Type:"))
self._security_lb.set_alignment(1.0, 0.5)
self._security_types = gtk.combo_box_new_text()
self._authMethods = [{"name":"none",
"desc":_("No Authentication")}]
self._security_types.append_text(self._authMethods[0]["desc"])
for name, desc in self.iface.authMethods(self.package):
self._authMethods.append({"name":name, "desc":desc})
self._security_types.append_text(desc)
self._set_current_security_type(_("No Authentication"))
self._pass_lb = gtk.Label(_("Password:"))
self._pass_lb.set_alignment(1.0, 0.5)
self._pass_txt = gtk.Entry()
self._pass_txt.set_visibility(False)
self._hide_cb = gtk.CheckButton(_("Hide Password"))
self._hide_cb.set_active(True)
if self.with_list:
table = gtk.Table(rows=4, columns=3)
self._wifiholder = WifiItemHolder()
self._scan_btn = gtk.Button(_("Scan"))
table.attach(self._essid_lb, 1, 2, 0, 1,
gtk.FILL, gtk.SHRINK)
table.attach(self._essid_txt, 2, 3, 0, 1,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._security_lb, 1, 2, 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._security_types, 2, 3, 1, 2,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._pass_lb, 1, 2, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._pass_txt, 2, 3, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._hide_cb, 1, 3, 3, 4,
gtk.FILL, gtk.SHRINK)
table.attach(self._wifiholder, 0, 1, 0, 3,
gtk.EXPAND | gtk.FILL, gtk.EXPAND | gtk.FILL)
table.attach(self._scan_btn, 0, 1, 3, 4,
gtk.FILL, gtk.SHRINK)
self._wifiholder.show()
else:
table = gtk.Table(rows=4, columns=2)
table.attach(self._essid_lb, 0, 1, 0, 1,
gtk.FILL, gtk.SHRINK)
table.attach(self._essid_txt, 1, 2, 0, 1,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._security_lb, 0, 1, 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._security_types, 1, 2, 1, 2,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._pass_lb, 0, 1, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._pass_txt, 1, 2, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._hide_cb, 0, 2, 3, 4,
gtk.FILL, gtk.SHRINK)
self.add(table)
table.show()
self._essid_lb.show()
self._essid_txt.show()
self._security_lb.show()
self._security_types.show()
def _listen_signals(self):
self._hide_cb.connect("clicked", self._on_hide_pass)
self._security_types.connect("changed", self._on_sec_changed)
def _insert_data(self, data):
self.device = data["device_id"]
self.if_available_set(data, "remote",
self._essid_txt.set_text)
caps = self.iface.capabilities(self.package)
modes = caps["modes"].split(",")
if self.with_list:
self.scan()
if "auth" in modes:
if not self.is_new:
authType = self.iface.authType(self.package,
self.connection)
self._set_current_security_type(authType)
self._show_password(False)
if (not authType == "none") & (not authType == ""):
info = self.iface.authInfo(self.package,
self.connection)
params = self.iface.authParameters(self.package,
authType)
if len(params) == 1:
password = info.values()[0]
self._pass_txt.set_text(password)
elif len(params) > 1:
print "\nTODO:Dynamic WEP Support"
self._show_password(True)
else:
self._security_types.set_active(0)
self._show_password(False)
else:
self._set_current_security_type(self.select_type)
def _on_hide_pass(self, widget):
self._pass_txt.set_visibility(not widget.get_active())
def _on_sec_changed(self, widget):
self._show_password(not widget.get_active() == 0)
def _show_password(self, state):
if not state:
self._hide_cb.hide()
self._pass_txt.hide()
self._pass_lb.hide()
else:
self._hide_cb.show()
self._pass_txt.show()
self._pass_lb.show()
def _get_current_security_type(self):
w = self._security_types
current = w.get_model()[w.get_active()][0]
for x in self._authMethods:
if x["desc"] == current:
return x["name"]
def _set_current_security_type(self, name):
for i, x in enumerate(self._authMethods):
if x["name"] == name:
self._security_types.set_active(i)
break
def scan(self, widget=None):
self._scan_btn.hide()
self._wifiholder.set_scanning(True)
self.iface.scanRemote(self.device ,
self.package,
self.listwifi)
def listwifi(self, package, exception, args):
self._scan_btn.show()
self._scan_btn.connect("clicked",
self.scan)
if not exception:
self._wifiholder.getConnections(args[0])
self._wifiholder.listen_change(self.on_wifi_clicked)
else:
print exception
def on_wifi_clicked(self, widget, callback_data):
data = callback_data["get_connection"]()
self._essid_txt.set_text(data["remote"])
self._set_current_security_type(data["encryption"])
def collect_data(self, data):
data["remote"] = self.get_text_of(self._essid_txt)
data["apmac"] = u"" #i think it is Access Point MAC
#Security
data["auth"] = unicode(self._get_current_security_type())
if data["auth"] != u"none":
params = self.iface.authParameters("wireless_tools",
data["auth"])
if len(params) == 1:
key = "auth_%s" % params[0][0]
data[key] = self.get_text_of(self._pass_txt)
else:
print "TODO:Dynamic WEP Support"
diff --git a/network_manager_gtk/windows.py b/network_manager_gtk/windows.py
index d76d972..26cf162 100644
--- a/network_manager_gtk/windows.py
+++ b/network_manager_gtk/windows.py
@@ -1,504 +1,389 @@
-#!/usr/bin/python
# -*- coding: utf-8 -*-
-
"""Network Manager gtk windows module
-MainWindow - Main Window
+
+BaseWindow - Base window for network_manager_gtk
EditWindow - Edit Settings Window
-NewWindow - New Profile Window
-NewEditWindow - heyya
+NewConnectionWindow - show new connections as a list
+NewConnectionEditWindow - new connection settings window
"""
-
#
-# Rıdvan Ãrsvuran (C) 2009
+# Rıdvan Ãrsvuran (C) 2009, 2010
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import gtk
import gobject
from network_manager_gtk.translation import _
from network_manager_gtk.widgets import ProfilesHolder
from network_manager_gtk.widgets import ProfileFrame
from network_manager_gtk.widgets import NetworkFrame
from network_manager_gtk.widgets import NameServerFrame
from network_manager_gtk.widgets import WirelessFrame
from network_manager_gtk.widgets import NewWifiConnectionItem
from network_manager_gtk.widgets import NewEthernetConnectionItem
class BaseWindow(gtk.Window):
"""BaseWindow for network_manager_gtk
"""
def __init__(self, iface):
"""init
Arguments:
- `iface`:
"""
gtk.Window.__init__(self)
self.iface = iface
self._set_style()
self._create_ui()
self._listen_signals()
def _set_style(self):
"""sets title and default size etc.
"""
pass
def _create_ui(self):
"""creates ui elements
"""
pass
def _listen_signals(self):
"""listens signals
"""
pass
gobject.type_register(BaseWindow)
-class MainWindow(BaseWindow):
- """Main Window
- profile list
- """
-
- def __init__(self, iface):
- """init MainWindow
-
- Arguments:
- - `iface`: backend.NetworkIface
- """
- BaseWindow.__init__(self, iface)
- self.get_state = lambda p,c:self.iface.info(p,c)[u"state"]
- self._get_profiles()
- def _set_style(self):
- self.set_title(_("Network Manager"))
- self.set_default_size(483, 300)
- def _create_ui(self):
- self._vbox = gtk.VBox()
- self.add(self._vbox)
-
- self._new_btn = gtk.Button(_('New Connection'))
- self._vbox.pack_start(self._new_btn, expand=False)
-
- self._holder = ProfilesHolder()
- self._holder.set_connection_signal(self._connection_callback)
- self._vbox.pack_start(self._holder)
- def _connection_callback(self, widget, data):
- """listens ConnectionWidget's signals
-
- Arguments:
- - `widget`: widget
- - `data`: {'action':(toggle | edit | delete)
- 'package':package_name,
- 'connection':connection_name}
- """
- action = data["action"]
- if action == "toggle":
- self.iface.toggle(data["package"],
- data["connection"])
- elif action == "edit":
- EditWindow(self.iface,
- data["package"],
- data["connection"]).show()
- else:
- m = _("Do you want to delete the connection '%s' ?") % \
- data['connection']
- dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING,
- buttons=gtk.BUTTONS_YES_NO,
- message_format=m)
- response = dialog.run()
- if response == gtk.RESPONSE_YES:
- try:
- self.iface.deleteConnection(data['package'],
- data['connection'])
- except Exception, e:
- print "Exception:",e
- dialog.destroy()
- def _listen_signals(self):
- """listen some signals
- """
- self._new_btn.connect("clicked", self.new_profile)
- self.connect("destroy", gtk.main_quit)
- self.iface.listen(self._listen_comar)
- def new_profile(self, widget):
- #TODO: classic mode support
- self.classic = False
- if self.classic:
- device = self.iface.devices("wireless_tools").keys()[0]
- EditWindow(self.iface,"wireless_tools", "new",
- device_id=device)
- else:
- NewConnectionWindow(self.iface).show()
- def _listen_comar(self, package, signal, args):
- """comar listener
-
- Arguments:
- - `package`: package
- - `signal`: signal type
- - `args`: arguments
- """
- args = map(lambda x: unicode(x), list(args))
- if signal == "stateChanged":
- self._holder.update_profile(package,
- args[0],
- args[1:])
- elif signal == "deviceChanged":
- print "TODO:Listen comar signal deviceChanged "
- elif signal == "connectionChanged":
- if args[0] == u"changed":
- pass#Nothing to do ?
- elif args[0] == u"added":
- self._holder.add_profile(package,
- args[1],
- self.get_state(package,
- args[1]))
- elif args[0] == u"deleted":
- self._holder.remove_profile(package,
- args[1])
- def _get_profiles(self):
- """get profiles from iface
- """
- for package in self.iface.packages():
- for connection in self.iface.connections(package):
- state = self.get_state(package, connection)
- self._holder.add_profile(package,
- connection,
- state)
-gobject.type_register(MainWindow)
-
class EditWindow(BaseWindow):
"""Edit Window
"""
def __init__(self, iface, package, connection,
device_id=None):
"""init
Arguments:
- `iface`: backend.NetworkIface
- `package`: package name
- `connection`: connection name (can be 'new')
"""
self._package = package
self._connection = connection
self._device_id = device_id
self.is_wireless = False
if self._package == "wireless_tools":
self.is_wireless = True
BaseWindow.__init__(self, iface)
def _set_style(self):
"""sets title and default size
"""
self.set_title(_("Edit Connection"))
self.set_modal(True)
if self.is_wireless:
self.set_default_size(644, 400)
else:
self.set_default_size(483, 300)
def _create_ui(self):
self.data = ""
self._is_new = self._connection == "new"
if not self._is_new:
self.data = self.iface.info(self._package,
self._connection)
self.is_up = self.data["state"][0:2] == "up"
else:
dname = self.iface.devices(self._package)[self._device_id]
self.data = {"name":"",
"device_id":self._device_id,
"device_name":dname,
"net_mode":"auto",
"name_mode":"default"}
self.is_up = False
vbox = gtk.VBox(homogeneous=False,
spacing=6)
self.add(vbox)
self.pf = ProfileFrame(self.data)
vbox.pack_start(self.pf, expand=False, fill=False)
if self.is_wireless:
self.wf = WirelessFrame(self.data, self.iface,
package=self._package,
connection=self._connection,
with_list=True,
is_new=self._is_new)
vbox.pack_start(self.wf, expand=True, fill=True)
self.wf.show()
self.nf = NetworkFrame(self.data)
vbox.pack_start(self.nf, expand=False, fill=False)
self.nsf = NameServerFrame(self.data)
vbox.pack_start(self.nsf, expand=False, fill=False)
self.nsf.show()
buttons = gtk.HBox(homogeneous=False,
spacing=6)
self.apply_btn = gtk.Button(_("Apply"))
self.cancel_btn = gtk.Button(_("Cancel"))
buttons.pack_end(self.apply_btn, expand=False, fill=False)
buttons.pack_end(self.cancel_btn, expand=False, fill=False)
buttons.show_all()
vbox.pack_end(buttons, expand=False, fill=False)
vbox.show()
def _listen_signals(self):
self.apply_btn.connect("clicked", self.apply)
self.cancel_btn.connect("clicked", self.cancel)
def cancel(self, widget):
self.destroy()
def apply(self, widget):
data = self.collect_data()
try:
self.iface.updateConnection(self._package,
data["name"],
data)
except Exception, e:
print "Exception:", unicode(e)
if not self._is_new:
if not self.data["name"] == data["name"]:
self.iface.deleteConnection(self._package,
self.data["name"])
if self.is_up:
self.iface.connect(self._package, data["name"])
self.destroy()
def collect_data(self):
data = {}
self.pf.collect_data(data)
self.nf.collect_data(data)
self.nsf.collect_data(data)
if self.is_wireless: self.wf.collect_data(data)
return data
gobject.type_register(EditWindow)
class NewConnectionWindow(BaseWindow):
- """show new connections as a list
- """
+ """show new connections as a list"""
def __init__(self, iface):
"""init
Arguments:
- `iface`: NetworkIface
"""
self._cons = [] #connections
BaseWindow.__init__(self, iface)
def _set_style(self):
self.set_title(_("New Connection"))
self.set_default_size(483, 300)
def _create_ui(self):
"""creates ui
"""
self._ui = gtk.VBox(homogeneous=False,
spacing=10)
self.add(self._ui)
self._ui.show()
self._refresh_btn = gtk.Button("")
self._ui.pack_start(self._refresh_btn,
expand=False)
self._refresh_btn.show()
self._list= gtk.VBox(homogeneous=True,
spacing=5)
self._ui.pack_start(self._list,
expand=False,
fill=False)
self._list.show_all()
self._show_list([]) #show none wireless connections
self.scan()
def _listen_signals(self):
self._refresh_btn.connect("clicked", self.scan)
def _set_scanning(self, status):
"""disable/enable refresh btn
Arguments:
- `status`: if True then disable button
"""
if status:
self._refresh_btn.set_label(_("Refreshing..."))
else:
self._refresh_btn.set_label(_("Refresh"))
self._refresh_btn.set_sensitive(not status)
def scan(self, widget=None):
"""scan for wifi networks
"""
#if user have wireless support
if self.get_devices("wireless_tools"):
self._set_scanning(True)
#TODO:more than one device support
d = self.get_devices("wireless_tools")[0]
self.iface.scanRemote(d, "wireless_tools",
self._scan_callback)
def get_devices(self, package):
"""returns devices of package
"""
return self.iface.devices(package).keys()
def _scan_callback(self, package, exception, args):
"""wifi scan callback
Arguments:
- `package`: package name
- `exception`: exception
- `args`: connection array
"""
self._set_scanning(False)
if not exception:
self._show_list(args[0])
else:
print exception
def create_new(self, widget, data):
NewConnectionEditWindow(self.iface,
data["package"],
data["device"],
data["connection"]).show()
def _show_list(self, connections):
"""show list
Arguments:
- `connections`: wireless connections array
"""
methods = self.iface.authMethods("wireless_tools")
def get_type(x):
for name, desc in methods:
if name == x:
return desc
#remove old ones
map(self._list.remove, self._cons)
self._cons = []
#add new ones
##ethernet
for device in self.get_devices("net_tools"):
name = self.iface.devices("net_tools")[device]
self.add_to_list(NewEthernetConnectionItem(device,
name))
##wireless
device_id = self.get_devices("wireless_tools")[0]
for connection in connections:
encryption = get_type(connection["encryption"])
self.add_to_list(NewWifiConnectionItem(device_id,
connection,
encryption))
self._list.show_all()
def add_to_list(self, item):
"""add connection item to list
- `item`: connection item
"""
self._list.pack_start(item,
expand=False,
fill=False)
self._cons.append(item)
item.on_connect(self.create_new)
gobject.type_register(NewConnectionWindow)
class NewConnectionEditWindow(BaseWindow):
- """New Connection Settings Window
- """
-
+ """New Connection Settings Window"""
def __init__(self, iface,
package, device, data):
self.package = package
self.data = data
self.device = device
BaseWindow.__init__(self, iface)
def _set_style(self):
self.set_title(_("Save Profile"))
self.set_default_size(483, 300)
def _create_ui(self):
dname = self.iface.devices(self.package)[self.device]
new_data = {"name":_("New Profile"),
"device_id":self.device,
"device_name":dname,
"net_mode":"auto",
"name_mode":"default"}
vbox = gtk.VBox(homogeneous=False,
spacing=5)
self.add(vbox)
self.pf = ProfileFrame(new_data)
vbox.pack_start(self.pf, expand=False, fill=False)
self.pf.show()
if self.package == "wireless_tools":
new_data["remote"] = self.data["remote"]
_type = self.data["encryption"]
self.wf = WirelessFrame(new_data,
self.iface,
package=self.package,
connection="new",
is_new=True,
with_list=False,
select_type=_type)
vbox.pack_start(self.wf, expand=False, fill=False)
self.wf.show()
self.expander = gtk.Expander(_("Other Settings"))
self.expander.set_expanded(False)
vbox2 = gtk.VBox()
self.expander.add(vbox2)
vbox.pack_start(self.expander, expand=False, fill=False)
self.expander.show()
self.nf = NetworkFrame(new_data)
vbox2.pack_start(self.nf, expand=False, fill=False)
self.nf.show()
self.nsf = NameServerFrame(new_data)
vbox2.pack_start(self.nsf, expand=False, fill=False)
self.nsf.show()
vbox2.show()
buttons = gtk.HBox(homogeneous=False,
spacing=6)
self.save_btn = gtk.Button(_("Save"))
self.save_and_connect_btn = gtk.Button(_("Save & Connect"))
self.cancel_btn = gtk.Button(_("Cancel"))
buttons.pack_end(self.save_and_connect_btn,
expand=False, fill=False)
buttons.pack_end(self.save_btn, expand=False, fill=False)
buttons.pack_end(self.cancel_btn, expand=False, fill=False)
buttons.show_all()
vbox.pack_end(buttons, expand=False, fill=False)
vbox.show()
def _listen_signals(self):
self.save_and_connect_btn.connect("clicked", self.save, True)
self.save_btn.connect("clicked", self.save, False)
self.cancel_btn.connect("clicked", self.cancel)
def cancel(self, widget):
self.destroy()
def save(self, widget, to_connect):
data = self.collect_data()
try:
self.iface.updateConnection(self.package,
data["name"],
data)
except Exception, e:
print "Exception:", unicode(e)
if to_connect:
self.iface.connect(self.package, data["name"])
self.destroy()
def collect_data(self):
data = {}
self.pf.collect_data(data)
self.nf.collect_data(data)
self.nsf.collect_data(data)
if self.package == "wireless_tools":
self.wf.collect_data(data)
return data
|
rdno/pardus-network-manager-gtk
|
6cf625baffdd180255743b864817bc8f62a5d968
|
added ethernet connection to NewConnectionWindow
|
diff --git a/README b/README
index 45e5aaf..595418a 100644
--- a/README
+++ b/README
@@ -1,23 +1,23 @@
Network Manager GTK is port of Pardus's network-manager.
It uses same backend of qt version.
To use:
Make mo files with
$ python make.py mo
and start program
$ python network-manager-gtk.py
It can
* activate/deactivate profiles
- * show and edit settings
- * create profile
+ * show and edit settings (Ethernet & Wireless)
+ * create profile (Ethernet & Wireless)
TODO
* error handling like no profile name
* Icon Support
* Tray Icon
* libnotify support
\ No newline at end of file
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index e8b95d2..f5289a6 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,748 +1,800 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
"""A special widget contains connection related stuff
"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
self._create_ui()
def _create_ui(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.set_mode(self._state.split(' '))
def set_mode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- `args`: [state, detail]
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
self._info.set_markup(states[args[0]]+':'+
'<span color="green">'+
args[1] +
'</span>')
def connect_signals(self, callback):
"""connect widgets signals
returns {'action':(toggle | edit | delete)
'package':package_name,
'connection':connection_name}
Arguments:
- `callback`: callback function
"""
self.check_btn.connect("pressed", callback,
{"action":"toggle",
"package":self._package_name,
"connection":self._connection_name})
self.edit_btn.connect("clicked", callback,
{"action":"edit",
"package":self._package_name,
"connection":self._connection_name})
self.delete_btn.connect("clicked", callback,
{"action":"delete",
"package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
class ProfilesHolder(gtk.ScrolledWindow):
"""Holds Profile List
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
self._vbox = gtk.VBox(homogeneous=False,
spacing=10)
self.add_with_viewport(self._vbox)
self._profiles = {}
def set_connection_signal(self, callback):
"""sets default callback for ConnectionWidget
"""
self._callback = callback
def add_profile(self, package, connection, state):
"""add profiles to vbox
"""
con_wg = ConnectionWidget(package,
connection,
state)
con_wg.connect_signals(self._callback)
self._vbox.pack_start(con_wg, expand=False, fill=False)
if not self._profiles.has_key(package):
self._profiles[package] = {}
self._profiles[package][connection] = {"state":state,
"widget":con_wg}
self._vbox.show_all()
def update_profile(self, package, connection, state):
"""update connection state
"""
c = self._profiles[package][connection]
c["state"] = state
c["widget"].set_mode(state)
def remove_profile(self, package, connection):
"""remove profile
"""
c = self._profiles[package][connection]
self._vbox.remove(c["widget"])
gobject.type_register(ProfilesHolder)
class WifiItemHolder(gtk.ScrolledWindow):
"""holder for wifi connections
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
return data
return None
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
if self.get_child():
self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
class NewWifiConnectionItem(gtk.Table):
"""new wifi connection
"""
def __init__(self,
device_id,
connection,
auth_type):
"""init
Arguments:
- `device_id`: connection device
- `connection`: scanRemote callback dict
example: {'remote':'ESSID Name',
'quality':'60',
'quality_max':'100'
'encryption':'wpa-psk',
...}
- `auth_type`: wpa-psk -> WPA Ortak Anahtar
"""
- gtk.Table.__init__(self, rows=3, columns=4)
+ gtk.Table.__init__(self, rows=3, columns=3)
self._device_id = device_id
- self._connection = connection;
+ self._connection = connection
self._type = auth_type
- self._create_ui();
+ self._create_ui()
def _create_ui(self):
"""creates UI
"""
frac = float(self._connection['quality'])/ \
float(self._connection['quality_max'])
per = self._connection['quality']
self._quality_bar = gtk.ProgressBar()
self._quality_bar.set_fraction(frac)
self._quality_bar.set_text(_("%d%%") % int(per))
self._name_txt = gtk.Label("")
self._name_txt.set_markup("<span color='blue'>" +
self._connection['remote']
+ "</span>")
self._name_txt.set_alignment(0.0 , 0.5)
self._encrypt_txt = gtk.Label(self._type)
self._encrypt_txt.set_alignment(0.0 , 0.5)
self._connect_btn = gtk.Button(_("Connect"))
self.set_row_spacings(5)
self.set_col_spacings(5)
self.attach(self._quality_bar, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._name_txt, 1, 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._encrypt_txt, 1, 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._connect_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(gtk.HSeparator(), 0, 3, 2, 3,
gtk.FILL, gtk.SHRINK)
def on_connect(self, func):
"""on connect button clicked
Arguments:
- - `func`:
+ - `func`: callback function
"""
self._connect_btn.connect("clicked",
func,
- {"connection":self._connection})
+ {"connection":self._connection,
+ "device": self._device_id,
+ "package": "wireless_tools"})
gobject.type_register(NewWifiConnectionItem)
+class NewEthernetConnectionItem(gtk.Table):
+ """new ethernet connection ite
+ """
+
+ def __init__(self, device_id, device_name):
+ """init
+
+ Arguments:
+ - `device_id`: device id
+ - `device_name`: device name to show user
+ """
+ gtk.Table.__init__(self, rows=3, columns=2)
+ self._device_id = device_id
+ self._device_name = device_name
+ self._create_ui()
+ def _create_ui(self):
+ """creates ui
+ """
+ self._name_lb = gtk.Label("")
+ self._name_lb.set_markup("<span color='blue'>" +
+ _("Ethernet")
+ + "</span>")
+ self._name_lb.set_alignment(0.0, 0.5)
+
+ self._device_name_lb = gtk.Label(self._device_name)
+ self._device_name_lb.set_alignment(0.0, 0.5)
+
+ self._connect_btn = gtk.Button(_("Connect"))
+
+ self.set_row_spacings(5)
+ self.set_col_spacings(5)
+ self.attach(self._name_lb, 0, 1, 0, 1,
+ gtk.EXPAND|gtk.FILL, gtk.SHRINK)
+ self.attach(self._device_name_lb, 0, 1, 1, 2,
+ gtk.EXPAND|gtk.FILL, gtk.SHRINK)
+ self.attach(self._connect_btn, 2, 3, 0, 2,
+ gtk.SHRINK, gtk.SHRINK)
+ self.attach(gtk.HSeparator(), 0, 3, 2, 3,
+ gtk.FILL, gtk.SHRINK)
+ def on_connect(self, func):
+ """on connect button clicked
+
+ Arguments:
+ - `func`:callback function
+ """
+ self._connect_btn.connect("clicked",
+ func,
+ {"connection":"",
+ "device":self._device_id,
+ "package":"net_tools"})
class EditWindowFrame(gtk.Frame):
"""Base EditWindowFrame
"""
def __init__(self, data):
"""init
Arguments:
- `data`: iface.info
"""
gtk.Frame.__init__(self)
self._create_ui()
self._listen_signals()
self._insert_data(data)
def _create_ui(self):
"""creates ui elements
"""
pass
def _listen_signals(self):
"""listens some signals
"""
pass
def _insert_data(self, data):
"""inserts data
Arguments:
- `data`:data to insert
"""
pass
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
def get_text_of(self, name):
"""gets text from widget in unicode"""
return unicode(name.get_text())
def collect_data(self, data):
"""collect data from ui and append datas to
given(data) dictionary"""
pass
def _rb_callback(self, widget, data):
"""RadioButton callback
Arguments:
- `widget`: widget
- `data`: callback data
"""
#if custom selected enable them
for i in data["enable"]:
i.set_sensitive(data["is_custom"])
#if custom selected disable them
for j in data["disable"]:
j.set_sensitive(not data["is_custom"])
def set_rb_signal(self, rb_list, custom_rb,
on_custom_enable,
on_custom_disable = []):
"""Sets RadioButton signals
and adjust behaviour
Arguments:
- `rb_list`: RadioButton list
- `custom_rb`: RadioButton labeled Custom
- `on_custom_enable`: List of widgets to enable
if custom selected
- `on_custom_disable`: List of widgets to disable
if custom selected
"""
for i in rb_list:
i.connect("clicked", self._rb_callback,
{"is_custom":i == custom_rb,
"enable":on_custom_enable,
"disable":on_custom_disable})
class ProfileFrame(EditWindowFrame):
"""Edit Window > Profile Frame
"""
def __init__(self, data):
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self.set_label(_("<b>Profile</b>"))
self.get_label_widget().set_use_markup(True)
profile_lb = gtk.Label(_("Profile Name:"))
self._profile_name = gtk.Entry()
self._device_name_lb = gtk.Label("")
self._device_name_lb.set_ellipsize(pango.ELLIPSIZE_MIDDLE)
#structure
hbox = gtk.HBox(homogeneous=False,
spacing=5)
self.add(hbox)
hbox.pack_start(profile_lb, expand=False)
hbox.pack_start(self._profile_name)
hbox.pack_start(self._device_name_lb)
self.show_all()
def _insert_data(self, data):
self.if_available_set(data, "name",
self._profile_name.set_text)
self.if_available_set(data, "device_name",
self._device_name_lb.set_text)
self.device_id = data["device_id"]
#TODO:more than one device support
def collect_data(self, data):
data["name"] = self.get_text_of(self._profile_name)
data["device_id"] = unicode(self.device_id)
class NetworkFrame(EditWindowFrame):
"""Edit Window > Network Settings Frame
"""
def __init__(self, data):
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self.set_label(_("<b>Network Settings</b>"))
self.get_label_widget().set_use_markup(True)
self._dhcp_rb = gtk.RadioButton(label=_("Use DHCP"))
self._custom_rb = gtk.RadioButton(group=self._dhcp_rb,
label=_("Use Manual Settings")
)
self._address_lb = gtk.Label(_("Address:"))
self._address_lb.set_alignment(1.0, 0.5)
self._mask_lb = gtk.Label(_("Network Mask:"))
self._mask_lb.set_alignment(1.0, 0.5)
self._gateway_lb = gtk.Label(_("Default Gateway:"))
self._gateway_lb.set_alignment(1.0, 0.5)
self._address_txt = gtk.Entry()
self._mask_txt = gtk.Entry()
self._gateway_txt = gtk.Entry()
custom = _("Custom")
self._custom_add_cb = gtk.CheckButton(label=custom)
self._custom_gate_cb = gtk.CheckButton(label=custom)
#structure
table = gtk.Table(rows=4, columns=4)
self.add(table)
table.attach(self._dhcp_rb, 0, 1 , 0, 1,
gtk.FILL, gtk.SHRINK)
table.attach(self._custom_rb, 0, 1 , 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._address_lb, 1, 2 , 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._mask_lb, 1, 2 , 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._gateway_lb, 1, 2 , 3, 4,
gtk.FILL, gtk.SHRINK)
table.attach(self._address_txt, 2, 3 , 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
table.attach(self._mask_txt, 2, 3, 2, 3,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
table.attach(self._gateway_txt, 2, 3 , 3, 4,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
table.attach(self._custom_add_cb, 3, 4 , 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._custom_gate_cb, 3, 4 , 3, 4,
gtk.FILL, gtk.SHRINK)
self.show_all()
def _listen_signals(self):
self._rb_list = [self._dhcp_rb, self._custom_rb]
self._on_custom_enable = [self._address_lb,
self._address_txt,
self._mask_lb,
self._mask_txt,
self._gateway_lb,
self._gateway_txt]
self._on_custom_disable = [self._custom_add_cb,
self._custom_gate_cb]
self.set_rb_signal(self._rb_list,
self._custom_rb,
self._on_custom_enable,
self._on_custom_disable)
self._custom_gate_cb.connect("clicked", self._on_custom)
self._custom_add_cb.connect("clicked", self._on_custom)
def _insert_data(self, data):
if data.has_key("net_mode"):
if data["net_mode"] == "auto":
self._dhcp_rb.set_active(True)
self._rb_callback(self._dhcp_rb,
{"is_custom":False,
"enable":self._on_custom_enable,
"disable":self._on_custom_disable})
if self.is_custom(data, "net_gateway"):
self._custom_gate_cb.set_active(True)
if self.is_custom(data, "net_address"):
self._custom_add_cb.set_active(True)
else:
self._custom_rb.set_active(False)
self.if_available_set(data, "net_address",
self._address_txt.set_text)
self.if_available_set(data, "net_mask",
self._mask_txt.set_text)
self.if_available_set(data, "net_gateway",
self._gateway_txt.set_text)
def _on_custom(self, widget):
if widget is self._custom_add_cb:
widgets = self._on_custom_enable[0:4]
else:
widgets = self._on_custom_enable[4:]
for x in widgets:
x.set_sensitive(widget.get_active())
def _rb_callback(self, widget, data):
EditWindowFrame._rb_callback(self, widget, data)
if not data["is_custom"]:
if self._custom_add_cb.get_active():
for x in data["enable"][0:4]:
x.set_sensitive(True)
if self._custom_gate_cb.get_active():
for x in data["enable"][4:]:
x.set_sensitive(True)
def is_custom(self, data, key):
if data.has_key(key):
if data[key] != "":
return True
return False
def collect_data(self, data):
data["net_mode"] = u"auto"
data["net_address"] = u""
data["net_mask"] = u""
data["net_gateway"] = u""
if self._custom_rb.get_active():
data["net_mode"] = u"manual"
if self._address_txt.state == gtk.STATE_NORMAL:
data["net_address"] = self.get_text_of(self._address_txt)
data["net_mask"] = self.get_text_of(self._mask_txt)
if self._gateway_txt.state == gtk.STATE_NORMAL:
data["net_gateway"] = self.get_text_of(self._gateway_txt)
class NameServerFrame(EditWindowFrame):
"""Edit Window > Name Server Frame
"""
def __init__(self, data):
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self.set_label(_("<b>Name Servers</b>"))
self.get_label_widget().set_use_markup(True)
self._default_rb = gtk.RadioButton(label=_("Default"))
self._auto_rb = gtk.RadioButton(group=self._default_rb,
label=_("Automatic"))
self._custom_rb = gtk.RadioButton(group=self._default_rb,
label=_("Custom"))
self._custom_txt = gtk.Entry()
#structure
hbox = gtk.HBox(homogeneous=False,
spacing=5)
self.add(hbox)
hbox.pack_start(self._default_rb, expand=False)
hbox.pack_start(self._auto_rb, expand=False)
hbox.pack_start(self._custom_rb, expand=False)
hbox.pack_start(self._custom_txt, expand=True)
self.show_all()
def _listen_signals(self):
self.set_rb_signal(rb_list=[self._default_rb,
self._auto_rb,
self._custom_rb],
custom_rb=self._custom_rb,
on_custom_enable=[self._custom_txt])
def _insert_data(self, data):
if data.has_key("name_mode"):
self._custom_txt.set_sensitive(False)
if data["name_mode"] == "default":
self._default_rb.set_active(True)
elif data["name_mode"] == "auto":
self._auto_rb.set_active(True)
elif data["name_mode"] == "custom":
self._custom_rb.set_active(True)
self._custom_txt.set_sensitive(True)
self.if_available_set(data, "name_server",
self._custom_txt.set_text)
def collect_data(self, data):
data["name_mode"] = u"default"
data["name_server"] = u""
if self._auto_rb.get_active():
data["name_mode"] = u"auto"
if self._custom_rb.get_active():
data["name_mode"] = u"custom"
data["name_server"] = self.get_text_of(self._custom_txt)
class WirelessFrame(EditWindowFrame):
"""Edit Settings Window > WirelessFrame
"""
def __init__(self, data, iface,
package=None,connection=None,
with_list=True, is_new=False,
select_type="none"):
self.iface = iface
self.package = package
self.connection = connection
self.with_list = with_list
self.is_new = is_new
self.select_type = select_type
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self.set_label(_("<b>Wireless</b>"))
self.get_label_widget().set_use_markup(True)
self._essid_lb = gtk.Label(_("ESSID:"))
self._essid_lb.set_alignment(1.0, 0.5)
self._essid_txt = gtk.Entry()
self._security_lb = gtk.Label(_("Security Type:"))
self._security_lb.set_alignment(1.0, 0.5)
self._security_types = gtk.combo_box_new_text()
self._authMethods = [{"name":"none",
"desc":_("No Authentication")}]
self._security_types.append_text(self._authMethods[0]["desc"])
for name, desc in self.iface.authMethods(self.package):
self._authMethods.append({"name":name, "desc":desc})
self._security_types.append_text(desc)
self._set_current_security_type(_("No Authentication"))
self._pass_lb = gtk.Label(_("Password:"))
self._pass_lb.set_alignment(1.0, 0.5)
self._pass_txt = gtk.Entry()
self._pass_txt.set_visibility(False)
self._hide_cb = gtk.CheckButton(_("Hide Password"))
self._hide_cb.set_active(True)
if self.with_list:
table = gtk.Table(rows=4, columns=3)
self._wifiholder = WifiItemHolder()
self._scan_btn = gtk.Button("Scan")
table.attach(self._essid_lb, 1, 2, 0, 1,
gtk.FILL, gtk.SHRINK)
table.attach(self._essid_txt, 2, 3, 0, 1,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._security_lb, 1, 2, 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._security_types, 2, 3, 1, 2,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._pass_lb, 1, 2, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._pass_txt, 2, 3, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._hide_cb, 1, 3, 3, 4,
gtk.FILL, gtk.SHRINK)
table.attach(self._wifiholder, 0, 1, 0, 3,
gtk.EXPAND | gtk.FILL, gtk.EXPAND | gtk.FILL)
table.attach(self._scan_btn, 0, 1, 3, 4,
gtk.FILL, gtk.SHRINK)
self._wifiholder.show()
else:
table = gtk.Table(rows=4, columns=2)
table.attach(self._essid_lb, 0, 1, 0, 1,
gtk.FILL, gtk.SHRINK)
table.attach(self._essid_txt, 1, 2, 0, 1,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._security_lb, 0, 1, 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._security_types, 1, 2, 1, 2,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._pass_lb, 0, 1, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._pass_txt, 1, 2, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._hide_cb, 0, 2, 3, 4,
gtk.FILL, gtk.SHRINK)
self.add(table)
table.show()
self._essid_lb.show()
self._essid_txt.show()
self._security_lb.show()
self._security_types.show()
def _listen_signals(self):
self._hide_cb.connect("clicked", self._on_hide_pass)
self._security_types.connect("changed", self._on_sec_changed)
def _insert_data(self, data):
self.device = data["device_id"]
self.if_available_set(data, "remote",
self._essid_txt.set_text)
caps = self.iface.capabilities(self.package)
modes = caps["modes"].split(",")
if self.with_list:
self.scan()
if "auth" in modes:
if not self.is_new:
authType = self.iface.authType(self.package,
self.connection)
self._set_current_security_type(authType)
self._show_password(False)
if (not authType == "none") & (not authType == ""):
info = self.iface.authInfo(self.package,
self.connection)
params = self.iface.authParameters(self.package,
authType)
if len(params) == 1:
password = info.values()[0]
self._pass_txt.set_text(password)
elif len(params) > 1:
print "\nTODO:Dynamic WEP Support"
self._show_password(True)
else:
self._security_types.set_active(0)
self._show_password(False)
else:
self._set_current_security_type(self.select_type)
def _on_hide_pass(self, widget):
self._pass_txt.set_visibility(not widget.get_active())
def _on_sec_changed(self, widget):
self._show_password(not widget.get_active() == 0)
def _show_password(self, state):
if not state:
self._hide_cb.hide()
self._pass_txt.hide()
self._pass_lb.hide()
else:
self._hide_cb.show()
self._pass_txt.show()
self._pass_lb.show()
def _get_current_security_type(self):
w = self._security_types
current = w.get_model()[w.get_active()][0]
for x in self._authMethods:
if x["desc"] == current:
return x["name"]
def _set_current_security_type(self, name):
for i, x in enumerate(self._authMethods):
if x["name"] == name:
self._security_types.set_active(i)
break
def scan(self, widget=None):
self._scan_btn.hide()
self._wifiholder.set_scanning(True)
self.iface.scanRemote(self.device ,
self.package,
self.listwifi)
def listwifi(self, package, exception, args):
self._scan_btn.show()
self._scan_btn.connect("clicked",
self.scan)
if not exception:
self._wifiholder.getConnections(args[0])
self._wifiholder.listen_change(self.on_wifi_clicked)
else:
print exception
def on_wifi_clicked(self, widget, callback_data):
data = callback_data["get_connection"]()
self._essid_txt.set_text(data["remote"])
self._set_current_security_type(data["encryption"])
def collect_data(self, data):
data["remote"] = self.get_text_of(self._essid_txt)
data["apmac"] = u"" #i think it is Access Point MAC
#Security
data["auth"] = unicode(self._get_current_security_type())
if data["auth"] != u"none":
params = self.iface.authParameters("wireless_tools",
data["auth"])
if len(params) == 1:
key = "auth_%s" % params[0][0]
data[key] = self.get_text_of(self._pass_txt)
else:
print "TODO:Dynamic WEP Support"
diff --git a/network_manager_gtk/windows.py b/network_manager_gtk/windows.py
index 312f37a..ed1b481 100644
--- a/network_manager_gtk/windows.py
+++ b/network_manager_gtk/windows.py
@@ -1,484 +1,504 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Network Manager gtk windows module
MainWindow - Main Window
EditWindow - Edit Settings Window
NewWindow - New Profile Window
NewEditWindow - heyya
"""
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import gtk
import gobject
from network_manager_gtk.translation import _
from network_manager_gtk.widgets import ProfilesHolder
from network_manager_gtk.widgets import ProfileFrame
from network_manager_gtk.widgets import NetworkFrame
from network_manager_gtk.widgets import NameServerFrame
from network_manager_gtk.widgets import WirelessFrame
from network_manager_gtk.widgets import NewWifiConnectionItem
+from network_manager_gtk.widgets import NewEthernetConnectionItem
class BaseWindow(gtk.Window):
"""BaseWindow for network_manager_gtk
"""
def __init__(self, iface):
"""init
Arguments:
- `iface`:
"""
gtk.Window.__init__(self)
self.iface = iface
self._set_style()
self._create_ui()
self._listen_signals()
def _set_style(self):
"""sets title and default size etc.
"""
pass
def _create_ui(self):
"""creates ui elements
"""
pass
def _listen_signals(self):
"""listens signals
"""
pass
gobject.type_register(BaseWindow)
class MainWindow(BaseWindow):
"""Main Window
profile list
"""
def __init__(self, iface):
"""init MainWindow
Arguments:
- `iface`: backend.NetworkIface
"""
BaseWindow.__init__(self, iface)
self.get_state = lambda p,c:self.iface.info(p,c)[u"state"]
self._get_profiles()
def _set_style(self):
self.set_title(_("Network Manager"))
self.set_default_size(483, 300)
def _create_ui(self):
self._vbox = gtk.VBox()
self.add(self._vbox)
self._new_btn = gtk.Button(_('New Connection'))
self._vbox.pack_start(self._new_btn, expand=False)
self._holder = ProfilesHolder()
self._holder.set_connection_signal(self._connection_callback)
self._vbox.pack_start(self._holder)
def _connection_callback(self, widget, data):
"""listens ConnectionWidget's signals
Arguments:
- `widget`: widget
- `data`: {'action':(toggle | edit | delete)
'package':package_name,
'connection':connection_name}
"""
action = data["action"]
if action == "toggle":
self.iface.toggle(data["package"],
data["connection"])
elif action == "edit":
EditWindow(self.iface,
data["package"],
data["connection"]).show()
else:
m = _("Do you wanna delete the connection '%s' ?") % \
data['connection']
dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING,
buttons=gtk.BUTTONS_YES_NO,
message_format=m)
response = dialog.run()
if response == gtk.RESPONSE_YES:
try:
self.iface.deleteConnection(data['package'],
data['connection'])
except Exception, e:
print "Exception:",e
dialog.destroy()
def _listen_signals(self):
"""listen some signals
"""
self._new_btn.connect("clicked", self.new_profile)
self.connect("destroy", gtk.main_quit)
self.iface.listen(self._listen_comar)
def new_profile(self, widget):
#TODO: classic mode support
self.classic = False
if self.classic:
device = self.iface.devices("wireless_tools").keys()[0]
EditWindow(self.iface,"wireless_tools", "new",
device_id=device)
else:
NewConnectionWindow(self.iface).show()
def _listen_comar(self, package, signal, args):
"""comar listener
Arguments:
- `package`: package
- `signal`: signal type
- `args`: arguments
"""
args = map(lambda x: unicode(x), list(args))
if signal == "stateChanged":
self._holder.update_profile(package,
args[0],
args[1:])
elif signal == "deviceChanged":
print "TODO:Listen comar signal deviceChanged "
elif signal == "connectionChanged":
if args[0] == u"changed":
pass#Nothing to do ?
elif args[0] == u"added":
self._holder.add_profile(package,
args[1],
self.get_state(package,
args[1]))
elif args[0] == u"deleted":
self._holder.remove_profile(package,
args[1])
def _get_profiles(self):
"""get profiles from iface
"""
for package in self.iface.packages():
for connection in self.iface.connections(package):
state = self.get_state(package, connection)
self._holder.add_profile(package,
connection,
state)
gobject.type_register(MainWindow)
class EditWindow(BaseWindow):
"""Edit Window
"""
def __init__(self, iface, package, connection,
device_id=None):
"""init
Arguments:
- `iface`: backend.NetworkIface
- `package`: package name
- `connection`: connection name (can be 'new')
"""
self._package = package
self._connection = connection
self._device_id = device_id
self.is_wireless = False
if self._package == "wireless_tools":
self.is_wireless = True
BaseWindow.__init__(self, iface)
def _set_style(self):
"""sets title and default size
"""
self.set_title(_("Edit Connection"))
self.set_modal(True)
if self.is_wireless:
self.set_default_size(644, 400)
else:
self.set_default_size(483, 300)
def _create_ui(self):
self.data = ""
self._is_new = self._connection == "new"
if not self._is_new:
self.data = self.iface.info(self._package,
self._connection)
self.is_up = self.data["state"][0:2] == "up"
else:
dname = self.iface.devices(self._package)[self._device_id]
self.data = {"name":"",
"device_id":self._device_id,
"device_name":dname,
"net_mode":"auto",
"name_mode":"default"}
self.is_up = False
vbox = gtk.VBox(homogeneous=False,
spacing=6)
self.add(vbox)
self.pf = ProfileFrame(self.data)
vbox.pack_start(self.pf, expand=False, fill=False)
if self.is_wireless:
self.wf = WirelessFrame(self.data, self.iface,
package=self._package,
connection=self._connection,
with_list=True,
is_new=self._is_new)
vbox.pack_start(self.wf, expand=True, fill=True)
self.wf.show()
self.nf = NetworkFrame(self.data)
vbox.pack_start(self.nf, expand=False, fill=False)
self.nsf = NameServerFrame(self.data)
vbox.pack_start(self.nsf, expand=False, fill=False)
self.nsf.show()
buttons = gtk.HBox(homogeneous=False,
spacing=6)
self.apply_btn = gtk.Button(_("Apply"))
self.cancel_btn = gtk.Button(_("Cancel"))
buttons.pack_end(self.apply_btn, expand=False, fill=False)
buttons.pack_end(self.cancel_btn, expand=False, fill=False)
buttons.show_all()
vbox.pack_end(buttons, expand=False, fill=False)
vbox.show()
def _listen_signals(self):
self.apply_btn.connect("clicked", self.apply)
self.cancel_btn.connect("clicked", self.cancel)
def cancel(self, widget):
self.destroy()
def apply(self, widget):
data = self.collect_data()
try:
self.iface.updateConnection(self._package,
data["name"],
data)
except Exception, e:
print "Exception:", unicode(e)
if not self._is_new:
if not self.data["name"] == data["name"]:
self.iface.deleteConnection(self._package,
self.data["name"])
if self.is_up:
self.iface.connect(self._package, data["name"])
self.destroy()
def collect_data(self):
data = {}
self.pf.collect_data(data)
self.nf.collect_data(data)
self.nsf.collect_data(data)
if self.is_wireless: self.wf.collect_data(data)
return data
gobject.type_register(EditWindow)
class NewConnectionWindow(BaseWindow):
"""show new connections as a list
"""
def __init__(self, iface):
"""init
Arguments:
- `iface`: NetworkIface
"""
- self._package = "wireless_tools"
self._cons = [] #connections
- self._devices = iface.devices(self._package).keys()
BaseWindow.__init__(self, iface)
def _set_style(self):
self.set_title(_("New Connection"))
self.set_default_size(483, 300)
def _create_ui(self):
"""creates ui
"""
self._ui = gtk.VBox(homogeneous=False,
spacing=10)
self.add(self._ui)
self._ui.show()
self._refresh_btn = gtk.Button("")
self._ui.pack_start(self._refresh_btn,
expand=False)
self._refresh_btn.show()
self._list= gtk.VBox(homogeneous=True,
spacing=5)
self._ui.pack_start(self._list,
expand=False,
fill=False)
self._list.show_all()
+ self._show_list([]) #show none wireless connections
self.scan()
def _listen_signals(self):
self._refresh_btn.connect("clicked", self.scan)
def _set_scanning(self, status):
"""disable/enable refresh btn
Arguments:
- `status`: if True then disable button
"""
if status:
self._refresh_btn.set_label(_("Refreshing..."))
else:
self._refresh_btn.set_label(_("Refresh"))
self._refresh_btn.set_sensitive(not status)
def scan(self, widget=None):
"""scan for wifi networks
"""
- self._set_scanning(True)
- d = self._devices[0] #TODO:more than one device support
- self.iface.scanRemote(d, self._package,
- self._scan_callback)
+ #if user have wireless support
+ if self.get_devices("wireless_tools"):
+ self._set_scanning(True)
+ #TODO:more than one device support
+ d = self.get_devices("wireless_tools")[0]
+ self.iface.scanRemote(d, "wireless_tools",
+ self._scan_callback)
+ def get_devices(self, package):
+ """returns devices of package
+ """
+ return self.iface.devices(package).keys()
def _scan_callback(self, package, exception, args):
"""wifi scan callback
Arguments:
- `package`: package name
- `exception`: exception
- `args`: connection array
"""
self._set_scanning(False)
if not exception:
self._show_list(args[0])
else:
print exception
def create_new(self, widget, data):
NewConnectionEditWindow(self.iface,
- "wireless_tools",
- self._devices[0],
+ data["package"],
+ data["device"],
data["connection"]).show()
def _show_list(self, connections):
"""show list
Arguments:
- - `connections`: connections array
+ - `connections`: wireless connections array
"""
- d = self._devices[0]
methods = self.iface.authMethods("wireless_tools")
def get_type(x):
for name, desc in methods:
if name == x:
return desc
#remove old ones
map(self._list.remove, self._cons)
self._cons = []
#add new ones
- for i, x in enumerate(connections):
- m = get_type(x["encryption"])
- self._cons.append(NewWifiConnectionItem(d, x, m))
- self._list.pack_start(self._cons[i],
- expand=False,
- fill=False)
- self._cons[i].on_connect(self.create_new)
+ ##ethernet
+ for device in self.get_devices("net_tools"):
+ name = self.iface.devices("net_tools")[device]
+ self.add_to_list(NewEthernetConnectionItem(device,
+ name))
+ ##wireless
+ device_id = self.get_devices("wireless_tools")[0]
+ for connection in connections:
+ encryption = get_type(connection["encryption"])
+ self.add_to_list(NewWifiConnectionItem(device_id,
+ connection,
+ encryption))
self._list.show_all()
+ def add_to_list(self, item):
+ """add connection item to list
+ - `item`: connection item
+ """
+ self._list.pack_start(item,
+ expand=False,
+ fill=False)
+ self._cons.append(item)
+ item.on_connect(self.create_new)
gobject.type_register(NewConnectionWindow)
class NewConnectionEditWindow(BaseWindow):
"""New Connection Settings Window
"""
def __init__(self, iface,
package, device, data):
self.package = package
self.data = data
self.device = device
BaseWindow.__init__(self, iface)
def _set_style(self):
self.set_title(_("Save Profile"))
self.set_default_size(483, 300)
def _create_ui(self):
dname = self.iface.devices(self.package)[self.device]
new_data = {"name":_("New Profile"),
"device_id":self.device,
"device_name":dname,
"net_mode":"auto",
"name_mode":"default"}
vbox = gtk.VBox(homogeneous=False,
spacing=5)
self.add(vbox)
self.pf = ProfileFrame(new_data)
vbox.pack_start(self.pf, expand=False, fill=False)
self.pf.show()
if self.package == "wireless_tools":
new_data["remote"] = self.data["remote"]
_type = self.data["encryption"]
self.wf = WirelessFrame(new_data,
self.iface,
package=self.package,
connection="new",
is_new=True,
with_list=False,
select_type=_type)
vbox.pack_start(self.wf, expand=False, fill=False)
self.wf.show()
self.expander = gtk.Expander(_("Other Settings"))
self.expander.set_expanded(False)
vbox2 = gtk.VBox()
self.expander.add(vbox2)
vbox.pack_start(self.expander, expand=False, fill=False)
self.expander.show()
self.nf = NetworkFrame(new_data)
vbox2.pack_start(self.nf, expand=False, fill=False)
self.nf.show()
self.nsf = NameServerFrame(new_data)
vbox2.pack_start(self.nsf, expand=False, fill=False)
self.nsf.show()
vbox2.show()
buttons = gtk.HBox(homogeneous=False,
spacing=6)
self.save_btn = gtk.Button(_("Save"))
self.save_and_connect_btn = gtk.Button(_("Save & Connect"))
self.cancel_btn = gtk.Button(_("Cancel"))
buttons.pack_end(self.save_and_connect_btn,
expand=False, fill=False)
buttons.pack_end(self.save_btn, expand=False, fill=False)
buttons.pack_end(self.cancel_btn, expand=False, fill=False)
buttons.show_all()
vbox.pack_end(buttons, expand=False, fill=False)
vbox.show()
def _listen_signals(self):
self.save_and_connect_btn.connect("clicked", self.save, True)
self.save_btn.connect("clicked", self.save, False)
self.cancel_btn.connect("clicked", self.cancel)
def cancel(self, widget):
self.destroy()
def save(self, widget, to_connect):
data = self.collect_data()
try:
self.iface.updateConnection(self.package,
data["name"],
data)
except Exception, e:
print "Exception:", unicode(e)
if to_connect:
self.iface.connect(self.package, data["name"])
self.destroy()
def collect_data(self):
data = {}
self.pf.collect_data(data)
self.nf.collect_data(data)
self.nsf.collect_data(data)
if self.package == "wireless_tools":
self.wf.collect_data(data)
return data
|
rdno/pardus-network-manager-gtk
|
1ec4ed6fe52a36dfab7ed94bbd9f666321daceba
|
It can create a profile
|
diff --git a/README b/README
index 85ab9b3..45e5aaf 100644
--- a/README
+++ b/README
@@ -1,22 +1,23 @@
-Network Manager GTK is port of Pardus network-manager.
+Network Manager GTK is port of Pardus's network-manager.
It uses same backend of qt version.
To use:
Make mo files with
$ python make.py mo
and start program
$ python network-manager-gtk.py
It can
* activate/deactivate profiles
* show and edit settings
+ * create profile
TODO
- * New Connection Interface
- * Icon Support
- * Tray Icon
- ? libnotify support
\ No newline at end of file
+ * error handling like no profile name
+ * Icon Support
+ * Tray Icon
+ * libnotify support
\ No newline at end of file
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index a7712ac..e8b95d2 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,732 +1,748 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
"""A special widget contains connection related stuff
"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
self._create_ui()
def _create_ui(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.set_mode(self._state.split(' '))
def set_mode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- `args`: [state, detail]
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
self._info.set_markup(states[args[0]]+':'+
'<span color="green">'+
args[1] +
'</span>')
def connect_signals(self, callback):
"""connect widgets signals
returns {'action':(toggle | edit | delete)
'package':package_name,
'connection':connection_name}
Arguments:
- `callback`: callback function
"""
self.check_btn.connect("pressed", callback,
{"action":"toggle",
"package":self._package_name,
"connection":self._connection_name})
self.edit_btn.connect("clicked", callback,
{"action":"edit",
"package":self._package_name,
"connection":self._connection_name})
self.delete_btn.connect("clicked", callback,
{"action":"delete",
"package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
class ProfilesHolder(gtk.ScrolledWindow):
"""Holds Profile List
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
self._vbox = gtk.VBox(homogeneous=False,
spacing=10)
self.add_with_viewport(self._vbox)
self._profiles = {}
def set_connection_signal(self, callback):
"""sets default callback for ConnectionWidget
"""
self._callback = callback
def add_profile(self, package, connection, state):
"""add profiles to vbox
"""
con_wg = ConnectionWidget(package,
connection,
state)
con_wg.connect_signals(self._callback)
self._vbox.pack_start(con_wg, expand=False, fill=False)
if not self._profiles.has_key(package):
self._profiles[package] = {}
self._profiles[package][connection] = {"state":state,
"widget":con_wg}
self._vbox.show_all()
def update_profile(self, package, connection, state):
"""update connection state
"""
c = self._profiles[package][connection]
c["state"] = state
c["widget"].set_mode(state)
def remove_profile(self, package, connection):
"""remove profile
"""
c = self._profiles[package][connection]
self._vbox.remove(c["widget"])
gobject.type_register(ProfilesHolder)
class WifiItemHolder(gtk.ScrolledWindow):
"""holder for wifi connections
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
return data
return None
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
if self.get_child():
self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
class NewWifiConnectionItem(gtk.Table):
"""new wifi connection
"""
def __init__(self,
device_id,
connection,
auth_type):
"""init
Arguments:
- `device_id`: connection device
- `connection`: scanRemote callback dict
example: {'remote':'ESSID Name',
'quality':'60',
'quality_max':'100'
'encryption':'wpa-psk',
...}
- `auth_type`: wpa-psk -> WPA Ortak Anahtar
"""
gtk.Table.__init__(self, rows=3, columns=4)
self._device_id = device_id
self._connection = connection;
self._type = auth_type
self._create_ui();
def _create_ui(self):
"""creates UI
"""
frac = float(self._connection['quality'])/ \
float(self._connection['quality_max'])
per = self._connection['quality']
self._quality_bar = gtk.ProgressBar()
self._quality_bar.set_fraction(frac)
self._quality_bar.set_text(_("%d%%") % int(per))
self._name_txt = gtk.Label("")
self._name_txt.set_markup("<span color='blue'>" +
self._connection['remote']
+ "</span>")
self._name_txt.set_alignment(0.0 , 0.5)
self._encrypt_txt = gtk.Label(self._type)
self._encrypt_txt.set_alignment(0.0 , 0.5)
self._connect_btn = gtk.Button(_("Connect"))
self.set_row_spacings(5)
self.set_col_spacings(5)
self.attach(self._quality_bar, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._name_txt, 1, 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._encrypt_txt, 1, 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._connect_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(gtk.HSeparator(), 0, 3, 2, 3,
gtk.FILL, gtk.SHRINK)
+ def on_connect(self, func):
+ """on connect button clicked
+
+ Arguments:
+ - `func`:
+ """
+ self._connect_btn.connect("clicked",
+ func,
+ {"connection":self._connection})
gobject.type_register(NewWifiConnectionItem)
class EditWindowFrame(gtk.Frame):
"""Base EditWindowFrame
"""
def __init__(self, data):
"""init
Arguments:
- `data`: iface.info
"""
gtk.Frame.__init__(self)
self._create_ui()
self._listen_signals()
self._insert_data(data)
def _create_ui(self):
"""creates ui elements
"""
pass
def _listen_signals(self):
"""listens some signals
"""
pass
def _insert_data(self, data):
"""inserts data
Arguments:
- `data`:data to insert
"""
pass
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
def get_text_of(self, name):
"""gets text from widget in unicode"""
return unicode(name.get_text())
def collect_data(self, data):
"""collect data from ui and append datas to
given(data) dictionary"""
pass
def _rb_callback(self, widget, data):
"""RadioButton callback
Arguments:
- `widget`: widget
- `data`: callback data
"""
#if custom selected enable them
for i in data["enable"]:
i.set_sensitive(data["is_custom"])
#if custom selected disable them
for j in data["disable"]:
j.set_sensitive(not data["is_custom"])
def set_rb_signal(self, rb_list, custom_rb,
on_custom_enable,
on_custom_disable = []):
"""Sets RadioButton signals
and adjust behaviour
Arguments:
- `rb_list`: RadioButton list
- `custom_rb`: RadioButton labeled Custom
- `on_custom_enable`: List of widgets to enable
if custom selected
- `on_custom_disable`: List of widgets to disable
if custom selected
"""
for i in rb_list:
i.connect("clicked", self._rb_callback,
{"is_custom":i == custom_rb,
"enable":on_custom_enable,
"disable":on_custom_disable})
class ProfileFrame(EditWindowFrame):
"""Edit Window > Profile Frame
"""
def __init__(self, data):
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self.set_label(_("<b>Profile</b>"))
self.get_label_widget().set_use_markup(True)
profile_lb = gtk.Label(_("Profile Name:"))
self._profile_name = gtk.Entry()
self._device_name_lb = gtk.Label("")
self._device_name_lb.set_ellipsize(pango.ELLIPSIZE_MIDDLE)
#structure
hbox = gtk.HBox(homogeneous=False,
spacing=5)
self.add(hbox)
hbox.pack_start(profile_lb, expand=False)
hbox.pack_start(self._profile_name)
hbox.pack_start(self._device_name_lb)
self.show_all()
def _insert_data(self, data):
self.if_available_set(data, "name",
self._profile_name.set_text)
self.if_available_set(data, "device_name",
self._device_name_lb.set_text)
self.device_id = data["device_id"]
#TODO:more than one device support
def collect_data(self, data):
data["name"] = self.get_text_of(self._profile_name)
data["device_id"] = unicode(self.device_id)
class NetworkFrame(EditWindowFrame):
"""Edit Window > Network Settings Frame
"""
def __init__(self, data):
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self.set_label(_("<b>Network Settings</b>"))
self.get_label_widget().set_use_markup(True)
self._dhcp_rb = gtk.RadioButton(label=_("Use DHCP"))
self._custom_rb = gtk.RadioButton(group=self._dhcp_rb,
label=_("Use Manual Settings")
)
self._address_lb = gtk.Label(_("Address:"))
self._address_lb.set_alignment(1.0, 0.5)
self._mask_lb = gtk.Label(_("Network Mask:"))
self._mask_lb.set_alignment(1.0, 0.5)
self._gateway_lb = gtk.Label(_("Default Gateway:"))
self._gateway_lb.set_alignment(1.0, 0.5)
self._address_txt = gtk.Entry()
self._mask_txt = gtk.Entry()
self._gateway_txt = gtk.Entry()
custom = _("Custom")
self._custom_add_cb = gtk.CheckButton(label=custom)
self._custom_gate_cb = gtk.CheckButton(label=custom)
#structure
table = gtk.Table(rows=4, columns=4)
self.add(table)
table.attach(self._dhcp_rb, 0, 1 , 0, 1,
gtk.FILL, gtk.SHRINK)
table.attach(self._custom_rb, 0, 1 , 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._address_lb, 1, 2 , 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._mask_lb, 1, 2 , 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._gateway_lb, 1, 2 , 3, 4,
gtk.FILL, gtk.SHRINK)
table.attach(self._address_txt, 2, 3 , 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
table.attach(self._mask_txt, 2, 3, 2, 3,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
table.attach(self._gateway_txt, 2, 3 , 3, 4,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
table.attach(self._custom_add_cb, 3, 4 , 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._custom_gate_cb, 3, 4 , 3, 4,
gtk.FILL, gtk.SHRINK)
self.show_all()
def _listen_signals(self):
self._rb_list = [self._dhcp_rb, self._custom_rb]
self._on_custom_enable = [self._address_lb,
self._address_txt,
self._mask_lb,
self._mask_txt,
self._gateway_lb,
self._gateway_txt]
self._on_custom_disable = [self._custom_add_cb,
self._custom_gate_cb]
self.set_rb_signal(self._rb_list,
self._custom_rb,
self._on_custom_enable,
self._on_custom_disable)
self._custom_gate_cb.connect("clicked", self._on_custom)
self._custom_add_cb.connect("clicked", self._on_custom)
def _insert_data(self, data):
if data.has_key("net_mode"):
if data["net_mode"] == "auto":
self._dhcp_rb.set_active(True)
self._rb_callback(self._dhcp_rb,
{"is_custom":False,
"enable":self._on_custom_enable,
"disable":self._on_custom_disable})
if self.is_custom(data, "net_gateway"):
self._custom_gate_cb.set_active(True)
if self.is_custom(data, "net_address"):
self._custom_add_cb.set_active(True)
else:
self._custom_rb.set_active(False)
self.if_available_set(data, "net_address",
self._address_txt.set_text)
self.if_available_set(data, "net_mask",
self._mask_txt.set_text)
self.if_available_set(data, "net_gateway",
self._gateway_txt.set_text)
def _on_custom(self, widget):
if widget is self._custom_add_cb:
widgets = self._on_custom_enable[0:4]
else:
widgets = self._on_custom_enable[4:]
for x in widgets:
x.set_sensitive(widget.get_active())
def _rb_callback(self, widget, data):
EditWindowFrame._rb_callback(self, widget, data)
if not data["is_custom"]:
if self._custom_add_cb.get_active():
for x in data["enable"][0:4]:
x.set_sensitive(True)
if self._custom_gate_cb.get_active():
for x in data["enable"][4:]:
x.set_sensitive(True)
def is_custom(self, data, key):
if data.has_key(key):
if data[key] != "":
return True
return False
def collect_data(self, data):
data["net_mode"] = u"auto"
data["net_address"] = u""
data["net_mask"] = u""
data["net_gateway"] = u""
if self._custom_rb.get_active():
data["net_mode"] = u"manual"
if self._address_txt.state == gtk.STATE_NORMAL:
data["net_address"] = self.get_text_of(self._address_txt)
data["net_mask"] = self.get_text_of(self._mask_txt)
if self._gateway_txt.state == gtk.STATE_NORMAL:
data["net_gateway"] = self.get_text_of(self._gateway_txt)
class NameServerFrame(EditWindowFrame):
"""Edit Window > Name Server Frame
"""
def __init__(self, data):
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self.set_label(_("<b>Name Servers</b>"))
self.get_label_widget().set_use_markup(True)
self._default_rb = gtk.RadioButton(label=_("Default"))
self._auto_rb = gtk.RadioButton(group=self._default_rb,
label=_("Automatic"))
self._custom_rb = gtk.RadioButton(group=self._default_rb,
label=_("Custom"))
self._custom_txt = gtk.Entry()
#structure
hbox = gtk.HBox(homogeneous=False,
spacing=5)
self.add(hbox)
hbox.pack_start(self._default_rb, expand=False)
hbox.pack_start(self._auto_rb, expand=False)
hbox.pack_start(self._custom_rb, expand=False)
hbox.pack_start(self._custom_txt, expand=True)
self.show_all()
def _listen_signals(self):
self.set_rb_signal(rb_list=[self._default_rb,
self._auto_rb,
self._custom_rb],
custom_rb=self._custom_rb,
on_custom_enable=[self._custom_txt])
def _insert_data(self, data):
if data.has_key("name_mode"):
self._custom_txt.set_sensitive(False)
if data["name_mode"] == "default":
self._default_rb.set_active(True)
elif data["name_mode"] == "auto":
self._auto_rb.set_active(True)
elif data["name_mode"] == "custom":
self._custom_rb.set_active(True)
self._custom_txt.set_sensitive(True)
self.if_available_set(data, "name_server",
self._custom_txt.set_text)
def collect_data(self, data):
data["name_mode"] = u"default"
data["name_server"] = u""
if self._auto_rb.get_active():
data["name_mode"] = u"auto"
if self._custom_rb.get_active():
data["name_mode"] = u"custom"
data["name_server"] = self.get_text_of(self._custom_txt)
class WirelessFrame(EditWindowFrame):
"""Edit Settings Window > WirelessFrame
"""
def __init__(self, data, iface,
package=None,connection=None,
- with_list=True, is_new=False):
+ with_list=True, is_new=False,
+ select_type="none"):
self.iface = iface
self.package = package
self.connection = connection
self.with_list = with_list
self.is_new = is_new
+ self.select_type = select_type
EditWindowFrame.__init__(self, data)
def _create_ui(self):
+ self.set_label(_("<b>Wireless</b>"))
+ self.get_label_widget().set_use_markup(True)
+
self._essid_lb = gtk.Label(_("ESSID:"))
self._essid_lb.set_alignment(1.0, 0.5)
self._essid_txt = gtk.Entry()
self._security_lb = gtk.Label(_("Security Type:"))
self._security_lb.set_alignment(1.0, 0.5)
self._security_types = gtk.combo_box_new_text()
self._authMethods = [{"name":"none",
"desc":_("No Authentication")}]
self._security_types.append_text(self._authMethods[0]["desc"])
for name, desc in self.iface.authMethods(self.package):
self._authMethods.append({"name":name, "desc":desc})
self._security_types.append_text(desc)
self._set_current_security_type(_("No Authentication"))
self._pass_lb = gtk.Label(_("Password:"))
self._pass_lb.set_alignment(1.0, 0.5)
self._pass_txt = gtk.Entry()
self._pass_txt.set_visibility(False)
self._hide_cb = gtk.CheckButton(_("Hide Password"))
self._hide_cb.set_active(True)
if self.with_list:
table = gtk.Table(rows=4, columns=3)
self._wifiholder = WifiItemHolder()
self._scan_btn = gtk.Button("Scan")
table.attach(self._essid_lb, 1, 2, 0, 1,
gtk.FILL, gtk.SHRINK)
table.attach(self._essid_txt, 2, 3, 0, 1,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._security_lb, 1, 2, 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._security_types, 2, 3, 1, 2,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._pass_lb, 1, 2, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._pass_txt, 2, 3, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._hide_cb, 1, 3, 3, 4,
gtk.FILL, gtk.SHRINK)
table.attach(self._wifiholder, 0, 1, 0, 3,
gtk.EXPAND | gtk.FILL, gtk.EXPAND | gtk.FILL)
table.attach(self._scan_btn, 0, 1, 3, 4,
gtk.FILL, gtk.SHRINK)
self._wifiholder.show()
else:
table = gtk.Table(rows=4, columns=2)
table.attach(self._essid_lb, 0, 1, 0, 1,
gtk.FILL, gtk.SHRINK)
table.attach(self._essid_txt, 1, 2, 0, 1,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._security_lb, 0, 1, 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._security_types, 1, 2, 1, 2,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._pass_lb, 0, 1, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._pass_txt, 1, 2, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._hide_cb, 0, 2, 3, 4,
gtk.FILL, gtk.SHRINK)
self.add(table)
table.show()
self._essid_lb.show()
self._essid_txt.show()
self._security_lb.show()
self._security_types.show()
def _listen_signals(self):
self._hide_cb.connect("clicked", self._on_hide_pass)
self._security_types.connect("changed", self._on_sec_changed)
def _insert_data(self, data):
self.device = data["device_id"]
self.if_available_set(data, "remote",
self._essid_txt.set_text)
caps = self.iface.capabilities(self.package)
modes = caps["modes"].split(",")
if self.with_list:
self.scan()
if "auth" in modes:
if not self.is_new:
authType = self.iface.authType(self.package,
self.connection)
self._set_current_security_type(authType)
self._show_password(False)
if (not authType == "none") & (not authType == ""):
info = self.iface.authInfo(self.package,
self.connection)
params = self.iface.authParameters(self.package,
authType)
if len(params) == 1:
password = info.values()[0]
self._pass_txt.set_text(password)
elif len(params) > 1:
print "\nTODO:Dynamic WEP Support"
self._show_password(True)
else:
self._security_types.set_active(0)
self._show_password(False)
+ else:
+ self._set_current_security_type(self.select_type)
def _on_hide_pass(self, widget):
self._pass_txt.set_visibility(not widget.get_active())
def _on_sec_changed(self, widget):
self._show_password(not widget.get_active() == 0)
def _show_password(self, state):
if not state:
self._hide_cb.hide()
self._pass_txt.hide()
self._pass_lb.hide()
else:
self._hide_cb.show()
self._pass_txt.show()
self._pass_lb.show()
def _get_current_security_type(self):
w = self._security_types
current = w.get_model()[w.get_active()][0]
for x in self._authMethods:
if x["desc"] == current:
return x["name"]
def _set_current_security_type(self, name):
for i, x in enumerate(self._authMethods):
if x["name"] == name:
self._security_types.set_active(i)
break
def scan(self, widget=None):
self._scan_btn.hide()
self._wifiholder.set_scanning(True)
self.iface.scanRemote(self.device ,
self.package,
self.listwifi)
def listwifi(self, package, exception, args):
self._scan_btn.show()
self._scan_btn.connect("clicked",
self.scan)
if not exception:
self._wifiholder.getConnections(args[0])
self._wifiholder.listen_change(self.on_wifi_clicked)
else:
print exception
def on_wifi_clicked(self, widget, callback_data):
data = callback_data["get_connection"]()
self._essid_txt.set_text(data["remote"])
self._set_current_security_type(data["encryption"])
def collect_data(self, data):
data["remote"] = self.get_text_of(self._essid_txt)
data["apmac"] = u"" #i think it is Access Point MAC
#Security
data["auth"] = unicode(self._get_current_security_type())
if data["auth"] != u"none":
params = self.iface.authParameters("wireless_tools",
data["auth"])
if len(params) == 1:
key = "auth_%s" % params[0][0]
data[key] = self.get_text_of(self._pass_txt)
else:
print "TODO:Dynamic WEP Support"
diff --git a/network_manager_gtk/windows.py b/network_manager_gtk/windows.py
index cc47f27..312f37a 100644
--- a/network_manager_gtk/windows.py
+++ b/network_manager_gtk/windows.py
@@ -1,383 +1,484 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Network Manager gtk windows module
MainWindow - Main Window
EditWindow - Edit Settings Window
NewWindow - New Profile Window
NewEditWindow - heyya
"""
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import gtk
import gobject
from network_manager_gtk.translation import _
from network_manager_gtk.widgets import ProfilesHolder
from network_manager_gtk.widgets import ProfileFrame
from network_manager_gtk.widgets import NetworkFrame
from network_manager_gtk.widgets import NameServerFrame
from network_manager_gtk.widgets import WirelessFrame
from network_manager_gtk.widgets import NewWifiConnectionItem
class BaseWindow(gtk.Window):
"""BaseWindow for network_manager_gtk
"""
def __init__(self, iface):
"""init
Arguments:
- `iface`:
"""
gtk.Window.__init__(self)
self.iface = iface
self._set_style()
self._create_ui()
self._listen_signals()
def _set_style(self):
"""sets title and default size etc.
"""
pass
def _create_ui(self):
"""creates ui elements
"""
pass
def _listen_signals(self):
"""listens signals
"""
pass
gobject.type_register(BaseWindow)
class MainWindow(BaseWindow):
"""Main Window
profile list
"""
def __init__(self, iface):
"""init MainWindow
Arguments:
- `iface`: backend.NetworkIface
"""
BaseWindow.__init__(self, iface)
self.get_state = lambda p,c:self.iface.info(p,c)[u"state"]
self._get_profiles()
def _set_style(self):
self.set_title(_("Network Manager"))
self.set_default_size(483, 300)
def _create_ui(self):
self._vbox = gtk.VBox()
self.add(self._vbox)
self._new_btn = gtk.Button(_('New Connection'))
self._vbox.pack_start(self._new_btn, expand=False)
self._holder = ProfilesHolder()
self._holder.set_connection_signal(self._connection_callback)
self._vbox.pack_start(self._holder)
def _connection_callback(self, widget, data):
"""listens ConnectionWidget's signals
Arguments:
- `widget`: widget
- `data`: {'action':(toggle | edit | delete)
'package':package_name,
'connection':connection_name}
"""
action = data["action"]
if action == "toggle":
self.iface.toggle(data["package"],
data["connection"])
elif action == "edit":
EditWindow(self.iface,
data["package"],
data["connection"]).show()
else:
m = _("Do you wanna delete the connection '%s' ?") % \
data['connection']
dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING,
buttons=gtk.BUTTONS_YES_NO,
message_format=m)
response = dialog.run()
if response == gtk.RESPONSE_YES:
try:
self.iface.deleteConnection(data['package'],
data['connection'])
except Exception, e:
print "Exception:",e
dialog.destroy()
def _listen_signals(self):
"""listen some signals
"""
self._new_btn.connect("clicked", self.new_profile)
self.connect("destroy", gtk.main_quit)
self.iface.listen(self._listen_comar)
def new_profile(self, widget):
#TODO: classic mode support
self.classic = False
if self.classic:
device = self.iface.devices("wireless_tools").keys()[0]
EditWindow(self.iface,"wireless_tools", "new",
device_id=device)
else:
NewConnectionWindow(self.iface).show()
def _listen_comar(self, package, signal, args):
"""comar listener
Arguments:
- `package`: package
- `signal`: signal type
- `args`: arguments
"""
args = map(lambda x: unicode(x), list(args))
if signal == "stateChanged":
self._holder.update_profile(package,
args[0],
args[1:])
elif signal == "deviceChanged":
print "TODO:Listen comar signal deviceChanged "
elif signal == "connectionChanged":
if args[0] == u"changed":
pass#Nothing to do ?
elif args[0] == u"added":
self._holder.add_profile(package,
args[1],
self.get_state(package,
args[1]))
elif args[0] == u"deleted":
self._holder.remove_profile(package,
args[1])
def _get_profiles(self):
"""get profiles from iface
"""
for package in self.iface.packages():
for connection in self.iface.connections(package):
state = self.get_state(package, connection)
self._holder.add_profile(package,
connection,
state)
gobject.type_register(MainWindow)
class EditWindow(BaseWindow):
"""Edit Window
"""
def __init__(self, iface, package, connection,
device_id=None):
"""init
Arguments:
- `iface`: backend.NetworkIface
- `package`: package name
- `connection`: connection name (can be 'new')
"""
self._package = package
self._connection = connection
self._device_id = device_id
self.is_wireless = False
if self._package == "wireless_tools":
self.is_wireless = True
BaseWindow.__init__(self, iface)
def _set_style(self):
"""sets title and default size
"""
self.set_title(_("Edit Connection"))
self.set_modal(True)
if self.is_wireless:
self.set_default_size(644, 400)
else:
self.set_default_size(483, 300)
def _create_ui(self):
self.data = ""
self._is_new = self._connection == "new"
if not self._is_new:
self.data = self.iface.info(self._package,
self._connection)
self.is_up = self.data["state"][0:2] == "up"
else:
dname = self.iface.devices(self._package)[self._device_id]
self.data = {"name":"",
"device_id":self._device_id,
"device_name":dname,
"net_mode":"auto",
"name_mode":"default"}
self.is_up = False
vbox = gtk.VBox(homogeneous=False,
spacing=6)
self.add(vbox)
self.pf = ProfileFrame(self.data)
vbox.pack_start(self.pf, expand=False, fill=False)
if self.is_wireless:
self.wf = WirelessFrame(self.data, self.iface,
package=self._package,
connection=self._connection,
with_list=True,
is_new=self._is_new)
vbox.pack_start(self.wf, expand=True, fill=True)
self.wf.show()
self.nf = NetworkFrame(self.data)
vbox.pack_start(self.nf, expand=False, fill=False)
self.nsf = NameServerFrame(self.data)
vbox.pack_start(self.nsf, expand=False, fill=False)
self.nsf.show()
buttons = gtk.HBox(homogeneous=False,
spacing=6)
self.apply_btn = gtk.Button(_("Apply"))
self.cancel_btn = gtk.Button(_("Cancel"))
buttons.pack_end(self.apply_btn, expand=False, fill=False)
buttons.pack_end(self.cancel_btn, expand=False, fill=False)
buttons.show_all()
vbox.pack_end(buttons, expand=False, fill=False)
vbox.show()
def _listen_signals(self):
self.apply_btn.connect("clicked", self.apply)
self.cancel_btn.connect("clicked", self.cancel)
def cancel(self, widget):
self.destroy()
def apply(self, widget):
data = self.collect_data()
try:
self.iface.updateConnection(self._package,
data["name"],
data)
except Exception, e:
print "Exception:", unicode(e)
if not self._is_new:
if not self.data["name"] == data["name"]:
self.iface.deleteConnection(self._package,
self.data["name"])
if self.is_up:
self.iface.connect(self._package, data["name"])
self.destroy()
def collect_data(self):
data = {}
self.pf.collect_data(data)
self.nf.collect_data(data)
self.nsf.collect_data(data)
if self.is_wireless: self.wf.collect_data(data)
return data
gobject.type_register(EditWindow)
class NewConnectionWindow(BaseWindow):
"""show new connections as a list
"""
def __init__(self, iface):
"""init
Arguments:
- `iface`: NetworkIface
"""
self._package = "wireless_tools"
self._cons = [] #connections
self._devices = iface.devices(self._package).keys()
BaseWindow.__init__(self, iface)
def _set_style(self):
self.set_title(_("New Connection"))
self.set_default_size(483, 300)
def _create_ui(self):
"""creates ui
"""
self._ui = gtk.VBox(homogeneous=False,
spacing=10)
self.add(self._ui)
self._ui.show()
self._refresh_btn = gtk.Button("")
self._ui.pack_start(self._refresh_btn,
expand=False)
self._refresh_btn.show()
self._list= gtk.VBox(homogeneous=True,
spacing=5)
self._ui.pack_start(self._list,
expand=False,
fill=False)
self._list.show_all()
self.scan()
def _listen_signals(self):
self._refresh_btn.connect("clicked", self.scan)
def _set_scanning(self, status):
"""disable/enable refresh btn
Arguments:
- `status`: if True then disable button
"""
if status:
self._refresh_btn.set_label(_("Refreshing..."))
else:
self._refresh_btn.set_label(_("Refresh"))
self._refresh_btn.set_sensitive(not status)
def scan(self, widget=None):
"""scan for wifi networks
"""
self._set_scanning(True)
d = self._devices[0] #TODO:more than one device support
self.iface.scanRemote(d, self._package,
self._scan_callback)
def _scan_callback(self, package, exception, args):
"""wifi scan callback
Arguments:
- `package`: package name
- `exception`: exception
- `args`: connection array
"""
self._set_scanning(False)
if not exception:
self._show_list(args[0])
else:
print exception
+ def create_new(self, widget, data):
+ NewConnectionEditWindow(self.iface,
+ "wireless_tools",
+ self._devices[0],
+ data["connection"]).show()
def _show_list(self, connections):
"""show list
Arguments:
- `connections`: connections array
"""
d = self._devices[0]
methods = self.iface.authMethods("wireless_tools")
def get_type(x):
for name, desc in methods:
if name == x:
return desc
#remove old ones
map(self._list.remove, self._cons)
self._cons = []
#add new ones
for i, x in enumerate(connections):
m = get_type(x["encryption"])
self._cons.append(NewWifiConnectionItem(d, x, m))
self._list.pack_start(self._cons[i],
expand=False,
fill=False)
+ self._cons[i].on_connect(self.create_new)
self._list.show_all()
gobject.type_register(NewConnectionWindow)
+
+class NewConnectionEditWindow(BaseWindow):
+ """New Connection Settings Window
+ """
+
+ def __init__(self, iface,
+ package, device, data):
+ self.package = package
+ self.data = data
+ self.device = device
+ BaseWindow.__init__(self, iface)
+ def _set_style(self):
+ self.set_title(_("Save Profile"))
+ self.set_default_size(483, 300)
+ def _create_ui(self):
+ dname = self.iface.devices(self.package)[self.device]
+ new_data = {"name":_("New Profile"),
+ "device_id":self.device,
+ "device_name":dname,
+ "net_mode":"auto",
+ "name_mode":"default"}
+ vbox = gtk.VBox(homogeneous=False,
+ spacing=5)
+ self.add(vbox)
+
+ self.pf = ProfileFrame(new_data)
+ vbox.pack_start(self.pf, expand=False, fill=False)
+ self.pf.show()
+ if self.package == "wireless_tools":
+ new_data["remote"] = self.data["remote"]
+ _type = self.data["encryption"]
+ self.wf = WirelessFrame(new_data,
+ self.iface,
+ package=self.package,
+ connection="new",
+ is_new=True,
+ with_list=False,
+ select_type=_type)
+ vbox.pack_start(self.wf, expand=False, fill=False)
+ self.wf.show()
+
+ self.expander = gtk.Expander(_("Other Settings"))
+ self.expander.set_expanded(False)
+ vbox2 = gtk.VBox()
+ self.expander.add(vbox2)
+ vbox.pack_start(self.expander, expand=False, fill=False)
+ self.expander.show()
+
+ self.nf = NetworkFrame(new_data)
+ vbox2.pack_start(self.nf, expand=False, fill=False)
+ self.nf.show()
+
+ self.nsf = NameServerFrame(new_data)
+ vbox2.pack_start(self.nsf, expand=False, fill=False)
+ self.nsf.show()
+
+ vbox2.show()
+
+ buttons = gtk.HBox(homogeneous=False,
+ spacing=6)
+ self.save_btn = gtk.Button(_("Save"))
+ self.save_and_connect_btn = gtk.Button(_("Save & Connect"))
+ self.cancel_btn = gtk.Button(_("Cancel"))
+ buttons.pack_end(self.save_and_connect_btn,
+ expand=False, fill=False)
+ buttons.pack_end(self.save_btn, expand=False, fill=False)
+ buttons.pack_end(self.cancel_btn, expand=False, fill=False)
+ buttons.show_all()
+ vbox.pack_end(buttons, expand=False, fill=False)
+ vbox.show()
+ def _listen_signals(self):
+ self.save_and_connect_btn.connect("clicked", self.save, True)
+ self.save_btn.connect("clicked", self.save, False)
+ self.cancel_btn.connect("clicked", self.cancel)
+ def cancel(self, widget):
+ self.destroy()
+ def save(self, widget, to_connect):
+ data = self.collect_data()
+ try:
+ self.iface.updateConnection(self.package,
+ data["name"],
+ data)
+ except Exception, e:
+ print "Exception:", unicode(e)
+ if to_connect:
+ self.iface.connect(self.package, data["name"])
+ self.destroy()
+ def collect_data(self):
+ data = {}
+ self.pf.collect_data(data)
+ self.nf.collect_data(data)
+ self.nsf.collect_data(data)
+ if self.package == "wireless_tools":
+ self.wf.collect_data(data)
+ return data
|
rdno/pardus-network-manager-gtk
|
58b9fa29ebd7d5676a52cb4a2e61d4ec79a6d6a5
|
deleted some old stuff;NewConnectionWindow moved to windows.py;
|
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index 07ea968..a7712ac 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,881 +1,732 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
"""A special widget contains connection related stuff
"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
self._create_ui()
def _create_ui(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.set_mode(self._state.split(' '))
def set_mode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- `args`: [state, detail]
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
self._info.set_markup(states[args[0]]+':'+
'<span color="green">'+
args[1] +
'</span>')
def connect_signals(self, callback):
"""connect widgets signals
returns {'action':(toggle | edit | delete)
'package':package_name,
'connection':connection_name}
Arguments:
- `callback`: callback function
"""
self.check_btn.connect("pressed", callback,
{"action":"toggle",
"package":self._package_name,
"connection":self._connection_name})
self.edit_btn.connect("clicked", callback,
{"action":"edit",
"package":self._package_name,
"connection":self._connection_name})
self.delete_btn.connect("clicked", callback,
{"action":"delete",
"package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
class ProfilesHolder(gtk.ScrolledWindow):
"""Holds Profile List
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
self._vbox = gtk.VBox(homogeneous=False,
spacing=10)
self.add_with_viewport(self._vbox)
self._profiles = {}
def set_connection_signal(self, callback):
"""sets default callback for ConnectionWidget
"""
self._callback = callback
def add_profile(self, package, connection, state):
"""add profiles to vbox
"""
con_wg = ConnectionWidget(package,
connection,
state)
con_wg.connect_signals(self._callback)
self._vbox.pack_start(con_wg, expand=False, fill=False)
if not self._profiles.has_key(package):
self._profiles[package] = {}
self._profiles[package][connection] = {"state":state,
"widget":con_wg}
self._vbox.show_all()
def update_profile(self, package, connection, state):
"""update connection state
"""
c = self._profiles[package][connection]
c["state"] = state
c["widget"].set_mode(state)
def remove_profile(self, package, connection):
"""remove profile
"""
c = self._profiles[package][connection]
self._vbox.remove(c["widget"])
gobject.type_register(ProfilesHolder)
class WifiItemHolder(gtk.ScrolledWindow):
"""holder for wifi connections
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
return data
return None
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
if self.get_child():
self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
class NewWifiConnectionItem(gtk.Table):
"""new wifi connection
"""
def __init__(self,
device_id,
- connection):
+ connection,
+ auth_type):
"""init
Arguments:
- `device_id`: connection device
- `connection`: scanRemote callback dict
example: {'remote':'ESSID Name',
'quality':'60',
'quality_max':'100'
'encryption':'wpa-psk',
...}
+ - `auth_type`: wpa-psk -> WPA Ortak Anahtar
"""
- gtk.Table.__init__(self, rows=2, columns=4)
+ gtk.Table.__init__(self, rows=3, columns=4)
self._device_id = device_id
self._connection = connection;
+ self._type = auth_type
self._create_ui();
def _create_ui(self):
"""creates UI
"""
frac = float(self._connection['quality'])/ \
float(self._connection['quality_max'])
per = self._connection['quality']
self._quality_bar = gtk.ProgressBar()
self._quality_bar.set_fraction(frac)
self._quality_bar.set_text(_("%d%%") % int(per))
- self._name_txt = gtk.Label(self._connection['remote'])
+ self._name_txt = gtk.Label("")
+ self._name_txt.set_markup("<span color='blue'>" +
+ self._connection['remote']
+ + "</span>")
self._name_txt.set_alignment(0.0 , 0.5)
- self._encrypt_txt = gtk.Label(self._connection['encryption'])
+ self._encrypt_txt = gtk.Label(self._type)
self._encrypt_txt.set_alignment(0.0 , 0.5)
self._connect_btn = gtk.Button(_("Connect"))
+
+ self.set_row_spacings(5)
+ self.set_col_spacings(5)
self.attach(self._quality_bar, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._name_txt, 1, 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._encrypt_txt, 1, 2, 1, 2,
- gtk.SHRINK, gtk.SHRINK)
+ gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._connect_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
+ self.attach(gtk.HSeparator(), 0, 3, 2, 3,
+ gtk.FILL, gtk.SHRINK)
gobject.type_register(NewWifiConnectionItem)
-class NewConnectionWindow(gtk.Window):
- """show new connections as a list
- """
-
- def __init__(self, iface):
- """init
- Arguments:
- - `iface`: NetworkIface
- """
- gtk.Window.__init__(self)
- self._iface = iface
- self.set_title(_("New Connection"))
- self._package = "wireless_tools"
- self._devices = self._iface.devices(self._package).keys()
- self._create_ui();
- self._cons = [] #connections
- self.scan()
- def _create_ui(self):
- """creates ui
- """
- self._ui = gtk.VBox()
- self.add(self._ui)
-
- self._refresh_btn = gtk.Button("")
- self._refresh_btn.connect("clicked", self.scan)
- self._ui.add(self._refresh_btn)
-
- self._list= gtk.VBox()
- self._ui.add(self._list)
- def _set_scanning(self, status):
- """disable/enable refresh btn
- Arguments:
- - `status`: if True then disable button
- """
- if status:
- self._refresh_btn.set_label(_("Refreshing..."))
- else:
- self._refresh_btn.set_label(_("Refresh"))
- self._refresh_btn.set_sensitive(not status)
- def scan(self, widget=None):
- """scan for wifi networks
- """
- self._set_scanning(True)
- d = self._devices[0] #TODO:more than one device support
- self._iface.scanRemote(d, self._package,
- self._scan_callback)
- def _scan_callback(self, package, exception, args):
- """wifi scan callback
-
- Arguments:
- - `package`: package name
- - `exception`: exception
- - `args`: connection array
- """
- self._set_scanning(False)
- if not exception:
- self._show_list(args[0])
- else:
- print exception
- def _show_list(self, connections):
- """show list
-
- Arguments:
- - `connections`: connections array
- """
- d = self._devices[0]
- #remove old ones
- map(self._list.remove, self._cons)
- self._cons = [NewWifiConnectionItem(d, x)
- for x in connections]
- #add new ones
- map(self._list.add, self._cons)
- self.show_all()
-
-gobject.type_register(NewConnectionWindow)
-
-class dummy_data_creator(object):
- """create
- """
-
- def __init__(self,
- device,
- device_name,
- essid=None):
- """init
- Arguments:
- - `device`:
- - `essid`:
- """
- self._wireless = False
- self._device = device
- self._device_name = device_name
- if essid is not None:
- self._essid = essid
- self._wireless = True
- def get(self):
- """get data
- """
- data = {}
- if self._wireless:
- data["name"] = self._essid
- else:
- data["name"] = "Kablo" #TODO: what?
- data["device_id"] = self._device
- data["device_name"] = self._device_name
- #Network Settings
- data["net_mode"] = "auto"
- data["net_address"] = ""
- data["net_mask"] = ""
- data["net_gateway"] = ""
- #Name Server Settings
- data["name_mode"] = "default"
- data["name_server"] = ""
- return data
-
-class MainInterface(object):
- """Imports main window glade
- """
-
- def __init__(self):
- """import glade
- """
- bind_glade_domain()
- self._xml = glade.XML("ui/main.glade")
- self._xml.signal_connect("on_window_main_destroy",
- gtk.main_quit)
- self._xml.signal_connect("on_new_clicked",
- self.show_news)
- self._window = self._xml.get_widget("window_main")
- self._holder = self._xml.get_widget("holder")
- self.iface = NetworkIface()
- def show_news(self, widget):
- a = NewConnectionWindow(self.iface)
- a.show()
- def brand_new(self, widget):
- """deneme
-
- Arguments:
-
- - `widget`:
- """
- pack = "net_tools"
- device = self.iface.devices(pack).keys()[0]
- name = self.iface.devices(pack)[device]
- a = EditInterface(pack,
- "",
- is_new=True,
- new_data=dummy_data_creator(device, name).get())
- a.getWindow().show()
-
- def getWindow(self):
- """returns window
- """
- return self._window
- def getHolder(self):
- """returns holder
- """
- return self._holder
-
-
class EditWindowFrame(gtk.Frame):
"""Base EditWindowFrame
"""
def __init__(self, data):
"""init
Arguments:
- `data`: iface.info
"""
gtk.Frame.__init__(self)
self._create_ui()
self._listen_signals()
self._insert_data(data)
def _create_ui(self):
"""creates ui elements
"""
pass
def _listen_signals(self):
"""listens some signals
"""
pass
def _insert_data(self, data):
"""inserts data
Arguments:
- `data`:data to insert
"""
pass
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
def get_text_of(self, name):
"""gets text from widget in unicode"""
return unicode(name.get_text())
def collect_data(self, data):
"""collect data from ui and append datas to
given(data) dictionary"""
pass
def _rb_callback(self, widget, data):
"""RadioButton callback
Arguments:
- `widget`: widget
- `data`: callback data
"""
#if custom selected enable them
for i in data["enable"]:
i.set_sensitive(data["is_custom"])
#if custom selected disable them
for j in data["disable"]:
j.set_sensitive(not data["is_custom"])
def set_rb_signal(self, rb_list, custom_rb,
on_custom_enable,
on_custom_disable = []):
"""Sets RadioButton signals
and adjust behaviour
Arguments:
- `rb_list`: RadioButton list
- `custom_rb`: RadioButton labeled Custom
- `on_custom_enable`: List of widgets to enable
if custom selected
- `on_custom_disable`: List of widgets to disable
if custom selected
"""
for i in rb_list:
i.connect("clicked", self._rb_callback,
{"is_custom":i == custom_rb,
"enable":on_custom_enable,
"disable":on_custom_disable})
class ProfileFrame(EditWindowFrame):
"""Edit Window > Profile Frame
"""
def __init__(self, data):
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self.set_label(_("<b>Profile</b>"))
self.get_label_widget().set_use_markup(True)
profile_lb = gtk.Label(_("Profile Name:"))
self._profile_name = gtk.Entry()
self._device_name_lb = gtk.Label("")
self._device_name_lb.set_ellipsize(pango.ELLIPSIZE_MIDDLE)
#structure
hbox = gtk.HBox(homogeneous=False,
spacing=5)
self.add(hbox)
hbox.pack_start(profile_lb, expand=False)
hbox.pack_start(self._profile_name)
hbox.pack_start(self._device_name_lb)
self.show_all()
def _insert_data(self, data):
self.if_available_set(data, "name",
self._profile_name.set_text)
self.if_available_set(data, "device_name",
self._device_name_lb.set_text)
self.device_id = data["device_id"]
#TODO:more than one device support
def collect_data(self, data):
data["name"] = self.get_text_of(self._profile_name)
data["device_id"] = unicode(self.device_id)
class NetworkFrame(EditWindowFrame):
"""Edit Window > Network Settings Frame
"""
def __init__(self, data):
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self.set_label(_("<b>Network Settings</b>"))
self.get_label_widget().set_use_markup(True)
self._dhcp_rb = gtk.RadioButton(label=_("Use DHCP"))
self._custom_rb = gtk.RadioButton(group=self._dhcp_rb,
label=_("Use Manual Settings")
)
self._address_lb = gtk.Label(_("Address:"))
self._address_lb.set_alignment(1.0, 0.5)
self._mask_lb = gtk.Label(_("Network Mask:"))
self._mask_lb.set_alignment(1.0, 0.5)
self._gateway_lb = gtk.Label(_("Default Gateway:"))
self._gateway_lb.set_alignment(1.0, 0.5)
self._address_txt = gtk.Entry()
self._mask_txt = gtk.Entry()
self._gateway_txt = gtk.Entry()
custom = _("Custom")
self._custom_add_cb = gtk.CheckButton(label=custom)
self._custom_gate_cb = gtk.CheckButton(label=custom)
#structure
table = gtk.Table(rows=4, columns=4)
self.add(table)
table.attach(self._dhcp_rb, 0, 1 , 0, 1,
gtk.FILL, gtk.SHRINK)
table.attach(self._custom_rb, 0, 1 , 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._address_lb, 1, 2 , 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._mask_lb, 1, 2 , 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._gateway_lb, 1, 2 , 3, 4,
gtk.FILL, gtk.SHRINK)
table.attach(self._address_txt, 2, 3 , 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
table.attach(self._mask_txt, 2, 3, 2, 3,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
table.attach(self._gateway_txt, 2, 3 , 3, 4,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
table.attach(self._custom_add_cb, 3, 4 , 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._custom_gate_cb, 3, 4 , 3, 4,
gtk.FILL, gtk.SHRINK)
self.show_all()
def _listen_signals(self):
self._rb_list = [self._dhcp_rb, self._custom_rb]
self._on_custom_enable = [self._address_lb,
self._address_txt,
self._mask_lb,
self._mask_txt,
self._gateway_lb,
self._gateway_txt]
self._on_custom_disable = [self._custom_add_cb,
self._custom_gate_cb]
self.set_rb_signal(self._rb_list,
self._custom_rb,
self._on_custom_enable,
self._on_custom_disable)
self._custom_gate_cb.connect("clicked", self._on_custom)
self._custom_add_cb.connect("clicked", self._on_custom)
def _insert_data(self, data):
if data.has_key("net_mode"):
if data["net_mode"] == "auto":
self._dhcp_rb.set_active(True)
self._rb_callback(self._dhcp_rb,
{"is_custom":False,
"enable":self._on_custom_enable,
"disable":self._on_custom_disable})
if self.is_custom(data, "net_gateway"):
self._custom_gate_cb.set_active(True)
if self.is_custom(data, "net_address"):
self._custom_add_cb.set_active(True)
else:
self._custom_rb.set_active(False)
self.if_available_set(data, "net_address",
self._address_txt.set_text)
self.if_available_set(data, "net_mask",
self._mask_txt.set_text)
self.if_available_set(data, "net_gateway",
self._gateway_txt.set_text)
def _on_custom(self, widget):
if widget is self._custom_add_cb:
widgets = self._on_custom_enable[0:4]
else:
widgets = self._on_custom_enable[4:]
for x in widgets:
x.set_sensitive(widget.get_active())
def _rb_callback(self, widget, data):
EditWindowFrame._rb_callback(self, widget, data)
if not data["is_custom"]:
if self._custom_add_cb.get_active():
for x in data["enable"][0:4]:
x.set_sensitive(True)
if self._custom_gate_cb.get_active():
for x in data["enable"][4:]:
x.set_sensitive(True)
def is_custom(self, data, key):
if data.has_key(key):
if data[key] != "":
return True
return False
def collect_data(self, data):
data["net_mode"] = u"auto"
data["net_address"] = u""
data["net_mask"] = u""
data["net_gateway"] = u""
if self._custom_rb.get_active():
data["net_mode"] = u"manual"
if self._address_txt.state == gtk.STATE_NORMAL:
data["net_address"] = self.get_text_of(self._address_txt)
data["net_mask"] = self.get_text_of(self._mask_txt)
if self._gateway_txt.state == gtk.STATE_NORMAL:
data["net_gateway"] = self.get_text_of(self._gateway_txt)
class NameServerFrame(EditWindowFrame):
"""Edit Window > Name Server Frame
"""
def __init__(self, data):
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self.set_label(_("<b>Name Servers</b>"))
self.get_label_widget().set_use_markup(True)
self._default_rb = gtk.RadioButton(label=_("Default"))
self._auto_rb = gtk.RadioButton(group=self._default_rb,
label=_("Automatic"))
self._custom_rb = gtk.RadioButton(group=self._default_rb,
label=_("Custom"))
self._custom_txt = gtk.Entry()
#structure
hbox = gtk.HBox(homogeneous=False,
spacing=5)
self.add(hbox)
hbox.pack_start(self._default_rb, expand=False)
hbox.pack_start(self._auto_rb, expand=False)
hbox.pack_start(self._custom_rb, expand=False)
hbox.pack_start(self._custom_txt, expand=True)
self.show_all()
def _listen_signals(self):
self.set_rb_signal(rb_list=[self._default_rb,
self._auto_rb,
self._custom_rb],
custom_rb=self._custom_rb,
on_custom_enable=[self._custom_txt])
def _insert_data(self, data):
if data.has_key("name_mode"):
self._custom_txt.set_sensitive(False)
if data["name_mode"] == "default":
self._default_rb.set_active(True)
elif data["name_mode"] == "auto":
self._auto_rb.set_active(True)
elif data["name_mode"] == "custom":
self._custom_rb.set_active(True)
self._custom_txt.set_sensitive(True)
self.if_available_set(data, "name_server",
self._custom_txt.set_text)
def collect_data(self, data):
data["name_mode"] = u"default"
data["name_server"] = u""
if self._auto_rb.get_active():
data["name_mode"] = u"auto"
if self._custom_rb.get_active():
data["name_mode"] = u"custom"
data["name_server"] = self.get_text_of(self._custom_txt)
class WirelessFrame(EditWindowFrame):
"""Edit Settings Window > WirelessFrame
"""
def __init__(self, data, iface,
package=None,connection=None,
with_list=True, is_new=False):
self.iface = iface
self.package = package
self.connection = connection
self.with_list = with_list
self.is_new = is_new
EditWindowFrame.__init__(self, data)
def _create_ui(self):
self._essid_lb = gtk.Label(_("ESSID:"))
self._essid_lb.set_alignment(1.0, 0.5)
self._essid_txt = gtk.Entry()
self._security_lb = gtk.Label(_("Security Type:"))
self._security_lb.set_alignment(1.0, 0.5)
self._security_types = gtk.combo_box_new_text()
self._authMethods = [{"name":"none",
"desc":_("No Authentication")}]
self._security_types.append_text(self._authMethods[0]["desc"])
for name, desc in self.iface.authMethods(self.package):
self._authMethods.append({"name":name, "desc":desc})
self._security_types.append_text(desc)
self._set_current_security_type(_("No Authentication"))
self._pass_lb = gtk.Label(_("Password:"))
self._pass_lb.set_alignment(1.0, 0.5)
self._pass_txt = gtk.Entry()
self._pass_txt.set_visibility(False)
self._hide_cb = gtk.CheckButton(_("Hide Password"))
self._hide_cb.set_active(True)
if self.with_list:
table = gtk.Table(rows=4, columns=3)
self._wifiholder = WifiItemHolder()
self._scan_btn = gtk.Button("Scan")
table.attach(self._essid_lb, 1, 2, 0, 1,
gtk.FILL, gtk.SHRINK)
table.attach(self._essid_txt, 2, 3, 0, 1,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._security_lb, 1, 2, 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._security_types, 2, 3, 1, 2,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._pass_lb, 1, 2, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._pass_txt, 2, 3, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._hide_cb, 1, 3, 3, 4,
gtk.FILL, gtk.SHRINK)
table.attach(self._wifiholder, 0, 1, 0, 3,
gtk.EXPAND | gtk.FILL, gtk.EXPAND | gtk.FILL)
table.attach(self._scan_btn, 0, 1, 3, 4,
gtk.FILL, gtk.SHRINK)
self._wifiholder.show()
else:
table = gtk.Table(rows=4, columns=2)
table.attach(self._essid_lb, 0, 1, 0, 1,
gtk.FILL, gtk.SHRINK)
table.attach(self._essid_txt, 1, 2, 0, 1,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._security_lb, 0, 1, 1, 2,
gtk.FILL, gtk.SHRINK)
table.attach(self._security_types, 1, 2, 1, 2,
gtk.EXPAND | gtk.FILL, gtk.SHRINK)
table.attach(self._pass_lb, 0, 1, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._pass_txt, 1, 2, 2, 3,
gtk.FILL, gtk.SHRINK)
table.attach(self._hide_cb, 0, 2, 3, 4,
gtk.FILL, gtk.SHRINK)
self.add(table)
table.show()
self._essid_lb.show()
self._essid_txt.show()
self._security_lb.show()
self._security_types.show()
def _listen_signals(self):
self._hide_cb.connect("clicked", self._on_hide_pass)
self._security_types.connect("changed", self._on_sec_changed)
def _insert_data(self, data):
self.device = data["device_id"]
self.if_available_set(data, "remote",
self._essid_txt.set_text)
caps = self.iface.capabilities(self.package)
modes = caps["modes"].split(",")
if self.with_list:
self.scan()
if "auth" in modes:
if not self.is_new:
authType = self.iface.authType(self.package,
self.connection)
self._set_current_security_type(authType)
self._show_password(False)
if (not authType == "none") & (not authType == ""):
info = self.iface.authInfo(self.package,
self.connection)
params = self.iface.authParameters(self.package,
authType)
if len(params) == 1:
password = info.values()[0]
self._pass_txt.set_text(password)
elif len(params) > 1:
print "\nTODO:Dynamic WEP Support"
self._show_password(True)
else:
self._security_types.set_active(0)
self._show_password(False)
def _on_hide_pass(self, widget):
self._pass_txt.set_visibility(not widget.get_active())
def _on_sec_changed(self, widget):
self._show_password(not widget.get_active() == 0)
def _show_password(self, state):
if not state:
self._hide_cb.hide()
self._pass_txt.hide()
self._pass_lb.hide()
else:
self._hide_cb.show()
self._pass_txt.show()
self._pass_lb.show()
def _get_current_security_type(self):
w = self._security_types
current = w.get_model()[w.get_active()][0]
for x in self._authMethods:
if x["desc"] == current:
return x["name"]
def _set_current_security_type(self, name):
for i, x in enumerate(self._authMethods):
if x["name"] == name:
self._security_types.set_active(i)
break
def scan(self, widget=None):
self._scan_btn.hide()
self._wifiholder.set_scanning(True)
self.iface.scanRemote(self.device ,
self.package,
self.listwifi)
def listwifi(self, package, exception, args):
self._scan_btn.show()
self._scan_btn.connect("clicked",
self.scan)
if not exception:
self._wifiholder.getConnections(args[0])
self._wifiholder.listen_change(self.on_wifi_clicked)
else:
print exception
def on_wifi_clicked(self, widget, callback_data):
data = callback_data["get_connection"]()
self._essid_txt.set_text(data["remote"])
self._set_current_security_type(data["encryption"])
def collect_data(self, data):
data["remote"] = self.get_text_of(self._essid_txt)
data["apmac"] = u"" #i think it is Access Point MAC
#Security
data["auth"] = unicode(self._get_current_security_type())
if data["auth"] != u"none":
params = self.iface.authParameters("wireless_tools",
data["auth"])
if len(params) == 1:
key = "auth_%s" % params[0][0]
data[key] = self.get_text_of(self._pass_txt)
else:
print "TODO:Dynamic WEP Support"
diff --git a/network_manager_gtk/windows.py b/network_manager_gtk/windows.py
index 7eb3486..cc47f27 100644
--- a/network_manager_gtk/windows.py
+++ b/network_manager_gtk/windows.py
@@ -1,274 +1,383 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Network Manager gtk windows module
MainWindow - Main Window
EditWindow - Edit Settings Window
NewWindow - New Profile Window
NewEditWindow - heyya
"""
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import gtk
+import gobject
from network_manager_gtk.translation import _
from network_manager_gtk.widgets import ProfilesHolder
from network_manager_gtk.widgets import ProfileFrame
from network_manager_gtk.widgets import NetworkFrame
from network_manager_gtk.widgets import NameServerFrame
from network_manager_gtk.widgets import WirelessFrame
+from network_manager_gtk.widgets import NewWifiConnectionItem
+
class BaseWindow(gtk.Window):
"""BaseWindow for network_manager_gtk
"""
def __init__(self, iface):
"""init
Arguments:
- `iface`:
"""
gtk.Window.__init__(self)
self.iface = iface
self._set_style()
self._create_ui()
self._listen_signals()
def _set_style(self):
"""sets title and default size etc.
"""
pass
def _create_ui(self):
"""creates ui elements
"""
pass
def _listen_signals(self):
"""listens signals
"""
pass
+gobject.type_register(BaseWindow)
+
class MainWindow(BaseWindow):
"""Main Window
profile list
"""
def __init__(self, iface):
"""init MainWindow
Arguments:
- `iface`: backend.NetworkIface
"""
BaseWindow.__init__(self, iface)
self.get_state = lambda p,c:self.iface.info(p,c)[u"state"]
self._get_profiles()
def _set_style(self):
self.set_title(_("Network Manager"))
self.set_default_size(483, 300)
def _create_ui(self):
self._vbox = gtk.VBox()
self.add(self._vbox)
self._new_btn = gtk.Button(_('New Connection'))
self._vbox.pack_start(self._new_btn, expand=False)
self._holder = ProfilesHolder()
self._holder.set_connection_signal(self._connection_callback)
self._vbox.pack_start(self._holder)
def _connection_callback(self, widget, data):
"""listens ConnectionWidget's signals
Arguments:
- `widget`: widget
- `data`: {'action':(toggle | edit | delete)
'package':package_name,
'connection':connection_name}
"""
action = data["action"]
if action == "toggle":
self.iface.toggle(data["package"],
data["connection"])
elif action == "edit":
EditWindow(self.iface,
data["package"],
data["connection"]).show()
else:
m = _("Do you wanna delete the connection '%s' ?") % \
data['connection']
dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING,
buttons=gtk.BUTTONS_YES_NO,
message_format=m)
response = dialog.run()
if response == gtk.RESPONSE_YES:
try:
self.iface.deleteConnection(data['package'],
data['connection'])
except Exception, e:
print "Exception:",e
dialog.destroy()
def _listen_signals(self):
"""listen some signals
"""
self._new_btn.connect("clicked", self.new_profile)
self.connect("destroy", gtk.main_quit)
self.iface.listen(self._listen_comar)
def new_profile(self, widget):
- EditWindow(self.iface,"wireless_tools", "new",
- device_id=self.iface.devices("wireless_tools").keys()[0]).show()
+ #TODO: classic mode support
+ self.classic = False
+ if self.classic:
+ device = self.iface.devices("wireless_tools").keys()[0]
+ EditWindow(self.iface,"wireless_tools", "new",
+ device_id=device)
+ else:
+ NewConnectionWindow(self.iface).show()
def _listen_comar(self, package, signal, args):
"""comar listener
Arguments:
- `package`: package
- `signal`: signal type
- `args`: arguments
"""
args = map(lambda x: unicode(x), list(args))
if signal == "stateChanged":
self._holder.update_profile(package,
args[0],
args[1:])
elif signal == "deviceChanged":
print "TODO:Listen comar signal deviceChanged "
elif signal == "connectionChanged":
if args[0] == u"changed":
pass#Nothing to do ?
elif args[0] == u"added":
self._holder.add_profile(package,
args[1],
self.get_state(package,
args[1]))
elif args[0] == u"deleted":
self._holder.remove_profile(package,
args[1])
def _get_profiles(self):
"""get profiles from iface
"""
for package in self.iface.packages():
for connection in self.iface.connections(package):
state = self.get_state(package, connection)
self._holder.add_profile(package,
connection,
state)
+gobject.type_register(MainWindow)
class EditWindow(BaseWindow):
"""Edit Window
"""
def __init__(self, iface, package, connection,
device_id=None):
"""init
Arguments:
- `iface`: backend.NetworkIface
- `package`: package name
- `connection`: connection name (can be 'new')
"""
self._package = package
self._connection = connection
self._device_id = device_id
self.is_wireless = False
if self._package == "wireless_tools":
self.is_wireless = True
BaseWindow.__init__(self, iface)
def _set_style(self):
"""sets title and default size
"""
self.set_title(_("Edit Connection"))
self.set_modal(True)
if self.is_wireless:
self.set_default_size(644, 400)
else:
self.set_default_size(483, 300)
def _create_ui(self):
self.data = ""
self._is_new = self._connection == "new"
if not self._is_new:
self.data = self.iface.info(self._package,
self._connection)
self.is_up = self.data["state"][0:2] == "up"
else:
dname = self.iface.devices(self._package)[self._device_id]
self.data = {"name":"",
"device_id":self._device_id,
"device_name":dname,
"net_mode":"auto",
"name_mode":"default"}
self.is_up = False
vbox = gtk.VBox(homogeneous=False,
spacing=6)
self.add(vbox)
self.pf = ProfileFrame(self.data)
vbox.pack_start(self.pf, expand=False, fill=False)
if self.is_wireless:
self.wf = WirelessFrame(self.data, self.iface,
package=self._package,
connection=self._connection,
with_list=True,
is_new=self._is_new)
vbox.pack_start(self.wf, expand=True, fill=True)
self.wf.show()
self.nf = NetworkFrame(self.data)
vbox.pack_start(self.nf, expand=False, fill=False)
self.nsf = NameServerFrame(self.data)
vbox.pack_start(self.nsf, expand=False, fill=False)
self.nsf.show()
buttons = gtk.HBox(homogeneous=False,
spacing=6)
self.apply_btn = gtk.Button(_("Apply"))
self.cancel_btn = gtk.Button(_("Cancel"))
buttons.pack_end(self.apply_btn, expand=False, fill=False)
buttons.pack_end(self.cancel_btn, expand=False, fill=False)
buttons.show_all()
vbox.pack_end(buttons, expand=False, fill=False)
vbox.show()
def _listen_signals(self):
self.apply_btn.connect("clicked", self.apply)
self.cancel_btn.connect("clicked", self.cancel)
def cancel(self, widget):
self.destroy()
def apply(self, widget):
data = self.collect_data()
try:
self.iface.updateConnection(self._package,
data["name"],
data)
except Exception, e:
print "Exception:", unicode(e)
if not self._is_new:
if not self.data["name"] == data["name"]:
self.iface.deleteConnection(self._package,
self.data["name"])
if self.is_up:
self.iface.connect(self._package, data["name"])
self.destroy()
def collect_data(self):
data = {}
self.pf.collect_data(data)
self.nf.collect_data(data)
self.nsf.collect_data(data)
if self.is_wireless: self.wf.collect_data(data)
return data
+
+gobject.type_register(EditWindow)
+
+class NewConnectionWindow(BaseWindow):
+ """show new connections as a list
+ """
+
+ def __init__(self, iface):
+ """init
+ Arguments:
+ - `iface`: NetworkIface
+ """
+ self._package = "wireless_tools"
+ self._cons = [] #connections
+ self._devices = iface.devices(self._package).keys()
+ BaseWindow.__init__(self, iface)
+ def _set_style(self):
+ self.set_title(_("New Connection"))
+ self.set_default_size(483, 300)
+ def _create_ui(self):
+ """creates ui
+ """
+ self._ui = gtk.VBox(homogeneous=False,
+ spacing=10)
+ self.add(self._ui)
+ self._ui.show()
+
+ self._refresh_btn = gtk.Button("")
+ self._ui.pack_start(self._refresh_btn,
+ expand=False)
+ self._refresh_btn.show()
+
+ self._list= gtk.VBox(homogeneous=True,
+ spacing=5)
+ self._ui.pack_start(self._list,
+ expand=False,
+ fill=False)
+ self._list.show_all()
+
+ self.scan()
+ def _listen_signals(self):
+ self._refresh_btn.connect("clicked", self.scan)
+ def _set_scanning(self, status):
+ """disable/enable refresh btn
+ Arguments:
+ - `status`: if True then disable button
+ """
+ if status:
+ self._refresh_btn.set_label(_("Refreshing..."))
+ else:
+ self._refresh_btn.set_label(_("Refresh"))
+ self._refresh_btn.set_sensitive(not status)
+ def scan(self, widget=None):
+ """scan for wifi networks
+ """
+ self._set_scanning(True)
+ d = self._devices[0] #TODO:more than one device support
+ self.iface.scanRemote(d, self._package,
+ self._scan_callback)
+ def _scan_callback(self, package, exception, args):
+ """wifi scan callback
+
+ Arguments:
+ - `package`: package name
+ - `exception`: exception
+ - `args`: connection array
+ """
+ self._set_scanning(False)
+ if not exception:
+ self._show_list(args[0])
+ else:
+ print exception
+ def _show_list(self, connections):
+ """show list
+
+ Arguments:
+ - `connections`: connections array
+ """
+ d = self._devices[0]
+ methods = self.iface.authMethods("wireless_tools")
+ def get_type(x):
+ for name, desc in methods:
+ if name == x:
+ return desc
+ #remove old ones
+ map(self._list.remove, self._cons)
+ self._cons = []
+ #add new ones
+ for i, x in enumerate(connections):
+ m = get_type(x["encryption"])
+ self._cons.append(NewWifiConnectionItem(d, x, m))
+ self._list.pack_start(self._cons[i],
+ expand=False,
+ fill=False)
+ self._list.show_all()
+
+gobject.type_register(NewConnectionWindow)
|
rdno/pardus-network-manager-gtk
|
4229cc6d3a34b285793622ea5e952dc133af0a83
|
no glade now; classic new connection works
|
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index d343c0f..07ea968 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,788 +1,881 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
"""A special widget contains connection related stuff
"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
self._create_ui()
def _create_ui(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.set_mode(self._state.split(' '))
def set_mode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- `args`: [state, detail]
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
self._info.set_markup(states[args[0]]+':'+
'<span color="green">'+
args[1] +
'</span>')
def connect_signals(self, callback):
"""connect widgets signals
returns {'action':(toggle | edit | delete)
'package':package_name,
'connection':connection_name}
Arguments:
- `callback`: callback function
"""
self.check_btn.connect("pressed", callback,
{"action":"toggle",
"package":self._package_name,
"connection":self._connection_name})
self.edit_btn.connect("clicked", callback,
{"action":"edit",
"package":self._package_name,
"connection":self._connection_name})
self.delete_btn.connect("clicked", callback,
{"action":"delete",
"package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
class ProfilesHolder(gtk.ScrolledWindow):
"""Holds Profile List
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
self._vbox = gtk.VBox(homogeneous=False,
spacing=10)
self.add_with_viewport(self._vbox)
self._profiles = {}
def set_connection_signal(self, callback):
"""sets default callback for ConnectionWidget
"""
self._callback = callback
def add_profile(self, package, connection, state):
"""add profiles to vbox
"""
con_wg = ConnectionWidget(package,
connection,
state)
con_wg.connect_signals(self._callback)
self._vbox.pack_start(con_wg, expand=False, fill=False)
if not self._profiles.has_key(package):
self._profiles[package] = {}
self._profiles[package][connection] = {"state":state,
"widget":con_wg}
self._vbox.show_all()
def update_profile(self, package, connection, state):
"""update connection state
"""
c = self._profiles[package][connection]
c["state"] = state
c["widget"].set_mode(state)
def remove_profile(self, package, connection):
"""remove profile
"""
c = self._profiles[package][connection]
self._vbox.remove(c["widget"])
gobject.type_register(ProfilesHolder)
class WifiItemHolder(gtk.ScrolledWindow):
"""holder for wifi connections
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
return data
return None
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
- self.remove(self.get_child())
+ if self.get_child():
+ self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
class NewWifiConnectionItem(gtk.Table):
"""new wifi connection
"""
def __init__(self,
device_id,
connection):
"""init
Arguments:
- `device_id`: connection device
- `connection`: scanRemote callback dict
example: {'remote':'ESSID Name',
'quality':'60',
'quality_max':'100'
'encryption':'wpa-psk',
...}
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._device_id = device_id
self._connection = connection;
self._create_ui();
def _create_ui(self):
"""creates UI
"""
frac = float(self._connection['quality'])/ \
float(self._connection['quality_max'])
per = self._connection['quality']
self._quality_bar = gtk.ProgressBar()
self._quality_bar.set_fraction(frac)
self._quality_bar.set_text(_("%d%%") % int(per))
self._name_txt = gtk.Label(self._connection['remote'])
self._name_txt.set_alignment(0.0 , 0.5)
self._encrypt_txt = gtk.Label(self._connection['encryption'])
self._encrypt_txt.set_alignment(0.0 , 0.5)
self._connect_btn = gtk.Button(_("Connect"))
self.attach(self._quality_bar, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._name_txt, 1, 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._encrypt_txt, 1, 2, 1, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._connect_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
gobject.type_register(NewWifiConnectionItem)
class NewConnectionWindow(gtk.Window):
"""show new connections as a list
"""
def __init__(self, iface):
"""init
Arguments:
- `iface`: NetworkIface
"""
gtk.Window.__init__(self)
self._iface = iface
self.set_title(_("New Connection"))
self._package = "wireless_tools"
self._devices = self._iface.devices(self._package).keys()
self._create_ui();
self._cons = [] #connections
self.scan()
def _create_ui(self):
"""creates ui
"""
self._ui = gtk.VBox()
self.add(self._ui)
self._refresh_btn = gtk.Button("")
self._refresh_btn.connect("clicked", self.scan)
self._ui.add(self._refresh_btn)
self._list= gtk.VBox()
self._ui.add(self._list)
def _set_scanning(self, status):
"""disable/enable refresh btn
Arguments:
- `status`: if True then disable button
"""
if status:
self._refresh_btn.set_label(_("Refreshing..."))
else:
self._refresh_btn.set_label(_("Refresh"))
self._refresh_btn.set_sensitive(not status)
def scan(self, widget=None):
"""scan for wifi networks
"""
self._set_scanning(True)
d = self._devices[0] #TODO:more than one device support
self._iface.scanRemote(d, self._package,
self._scan_callback)
def _scan_callback(self, package, exception, args):
"""wifi scan callback
Arguments:
- `package`: package name
- `exception`: exception
- `args`: connection array
"""
self._set_scanning(False)
if not exception:
self._show_list(args[0])
else:
print exception
def _show_list(self, connections):
"""show list
Arguments:
- `connections`: connections array
"""
d = self._devices[0]
#remove old ones
map(self._list.remove, self._cons)
self._cons = [NewWifiConnectionItem(d, x)
for x in connections]
#add new ones
map(self._list.add, self._cons)
self.show_all()
gobject.type_register(NewConnectionWindow)
class dummy_data_creator(object):
"""create
"""
def __init__(self,
device,
device_name,
essid=None):
"""init
Arguments:
- `device`:
- `essid`:
"""
self._wireless = False
self._device = device
self._device_name = device_name
if essid is not None:
self._essid = essid
self._wireless = True
def get(self):
"""get data
"""
data = {}
if self._wireless:
data["name"] = self._essid
else:
data["name"] = "Kablo" #TODO: what?
data["device_id"] = self._device
data["device_name"] = self._device_name
#Network Settings
data["net_mode"] = "auto"
data["net_address"] = ""
data["net_mask"] = ""
data["net_gateway"] = ""
#Name Server Settings
data["name_mode"] = "default"
data["name_server"] = ""
return data
class MainInterface(object):
"""Imports main window glade
"""
def __init__(self):
"""import glade
"""
bind_glade_domain()
self._xml = glade.XML("ui/main.glade")
self._xml.signal_connect("on_window_main_destroy",
gtk.main_quit)
self._xml.signal_connect("on_new_clicked",
self.show_news)
self._window = self._xml.get_widget("window_main")
self._holder = self._xml.get_widget("holder")
self.iface = NetworkIface()
def show_news(self, widget):
a = NewConnectionWindow(self.iface)
a.show()
def brand_new(self, widget):
"""deneme
Arguments:
- `widget`:
"""
pack = "net_tools"
device = self.iface.devices(pack).keys()[0]
name = self.iface.devices(pack)[device]
a = EditInterface(pack,
"",
is_new=True,
new_data=dummy_data_creator(device, name).get())
a.getWindow().show()
def getWindow(self):
"""returns window
"""
return self._window
def getHolder(self):
"""returns holder
"""
return self._holder
-# --- Edit Window Sections (in ui: frame)
-class EditSection(object):
- def __init__(self, parent):
- super(EditSection, self).__init__()
- self.get = parent.get
- self.signal_connect = parent._xml.signal_connect
- self.parent = parent
+class EditWindowFrame(gtk.Frame):
+ """Base EditWindowFrame
+ """
+
+ def __init__(self, data):
+ """init
+
+ Arguments:
+ - `data`: iface.info
+ """
+ gtk.Frame.__init__(self)
+ self._create_ui()
+ self._listen_signals()
+ self._insert_data(data)
+ def _create_ui(self):
+ """creates ui elements
+ """
+ pass
+ def _listen_signals(self):
+ """listens some signals
+ """
+ pass
+ def _insert_data(self, data):
+ """inserts data
+
+ Arguments:
+ - `data`:data to insert
+ """
+ pass
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
def get_text_of(self, name):
"""gets text from widget in unicode"""
- return unicode(self.get(name).get_text())
+ return unicode(name.get_text())
def collect_data(self, data):
"""collect data from ui and append datas to
given(data) dictionary"""
pass
+ def _rb_callback(self, widget, data):
+ """RadioButton callback
-class ProfileSection(EditSection):
- def __init__(self, parent):
- super(ProfileSection, self).__init__(parent)
- def insert_data_and_show(self, data):
+ Arguments:
+ - `widget`: widget
+ - `data`: callback data
+ """
+ #if custom selected enable them
+ for i in data["enable"]:
+ i.set_sensitive(data["is_custom"])
+ #if custom selected disable them
+ for j in data["disable"]:
+ j.set_sensitive(not data["is_custom"])
+ def set_rb_signal(self, rb_list, custom_rb,
+ on_custom_enable,
+ on_custom_disable = []):
+ """Sets RadioButton signals
+ and adjust behaviour
+
+ Arguments:
+ - `rb_list`: RadioButton list
+ - `custom_rb`: RadioButton labeled Custom
+ - `on_custom_enable`: List of widgets to enable
+ if custom selected
+ - `on_custom_disable`: List of widgets to disable
+ if custom selected
+ """
+ for i in rb_list:
+ i.connect("clicked", self._rb_callback,
+ {"is_custom":i == custom_rb,
+ "enable":on_custom_enable,
+ "disable":on_custom_disable})
+class ProfileFrame(EditWindowFrame):
+ """Edit Window > Profile Frame
+ """
+ def __init__(self, data):
+ EditWindowFrame.__init__(self, data)
+ def _create_ui(self):
+ self.set_label(_("<b>Profile</b>"))
+ self.get_label_widget().set_use_markup(True)
+
+ profile_lb = gtk.Label(_("Profile Name:"))
+ self._profile_name = gtk.Entry()
+
+ self._device_name_lb = gtk.Label("")
+ self._device_name_lb.set_ellipsize(pango.ELLIPSIZE_MIDDLE)
+
+ #structure
+ hbox = gtk.HBox(homogeneous=False,
+ spacing=5)
+ self.add(hbox)
+ hbox.pack_start(profile_lb, expand=False)
+ hbox.pack_start(self._profile_name)
+ hbox.pack_start(self._device_name_lb)
+ self.show_all()
+ def _insert_data(self, data):
self.if_available_set(data, "name",
- self.get("profilename").set_text)
+ self._profile_name.set_text)
self.if_available_set(data, "device_name",
- self.get("device_name_label").set_text)
+ self._device_name_lb.set_text)
self.device_id = data["device_id"]
#TODO:more than one device support
def collect_data(self, data):
- super(ProfileSection, self).collect_data(data)
- data["name"] = self.get_text_of("profilename")
+ data["name"] = self.get_text_of(self._profile_name)
data["device_id"] = unicode(self.device_id)
-class NetworkSettingsSection(EditSection):
- def __init__(self, parent):
- super(NetworkSettingsSection, self).__init__(parent)
- def _on_type_changed(self, widget):
- if widget is self.get("dhcp_rb"):
- self.set_manual_network(False)
- else:
- self.set_manual_network(True)
- def set_manual_network(self, state):
- self.get("address").set_sensitive(state)
- self.get("address_lb").set_sensitive(state)
- self.get("networkmask").set_sensitive(state)
- self.get("networkmask_lb").set_sensitive(state)
- self.get("gateway").set_sensitive(state)
- self.get("gateway_lb").set_sensitive(state)
- # custom things
- self.get("custom_gateway").set_sensitive(not state)
- self.get("custom_address").set_sensitive(not state)
- if not state:
- self._on_custom_address(self.get("custom_address"))
- self._on_custom_gateway(self.get("custom_gateway"))
- def _on_custom_address(self, widget):
- state = widget.get_active()
- self.get("address").set_sensitive(state)
- self.get("address_lb").set_sensitive(state)
- self.get("networkmask").set_sensitive(state)
- self.get("networkmask_lb").set_sensitive(state)
- def _on_custom_gateway(self, widget):
- state = widget.get_active()
- self.get("gateway").set_sensitive(state)
- self.get("gateway_lb").set_sensitive(state)
- def listen_signals(self):
- self.signal_connect("on_dhcp_rb_clicked",
- self._on_type_changed)
- self.signal_connect("on_manual_rb_clicked",
- self._on_type_changed)
- self.signal_connect("on_custom_gateway_toggled",
- self._on_custom_gateway)
- self.signal_connect("on_custom_address_toggled",
- self._on_custom_address)
- def insert_data_and_show(self, data):
+class NetworkFrame(EditWindowFrame):
+ """Edit Window > Network Settings Frame
+ """
+
+ def __init__(self, data):
+ EditWindowFrame.__init__(self, data)
+ def _create_ui(self):
+ self.set_label(_("<b>Network Settings</b>"))
+ self.get_label_widget().set_use_markup(True)
+
+ self._dhcp_rb = gtk.RadioButton(label=_("Use DHCP"))
+ self._custom_rb = gtk.RadioButton(group=self._dhcp_rb,
+ label=_("Use Manual Settings")
+ )
+ self._address_lb = gtk.Label(_("Address:"))
+ self._address_lb.set_alignment(1.0, 0.5)
+ self._mask_lb = gtk.Label(_("Network Mask:"))
+ self._mask_lb.set_alignment(1.0, 0.5)
+ self._gateway_lb = gtk.Label(_("Default Gateway:"))
+ self._gateway_lb.set_alignment(1.0, 0.5)
+
+ self._address_txt = gtk.Entry()
+ self._mask_txt = gtk.Entry()
+ self._gateway_txt = gtk.Entry()
+
+ custom = _("Custom")
+ self._custom_add_cb = gtk.CheckButton(label=custom)
+ self._custom_gate_cb = gtk.CheckButton(label=custom)
+
+ #structure
+ table = gtk.Table(rows=4, columns=4)
+ self.add(table)
+
+ table.attach(self._dhcp_rb, 0, 1 , 0, 1,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._custom_rb, 0, 1 , 1, 2,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._address_lb, 1, 2 , 1, 2,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._mask_lb, 1, 2 , 2, 3,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._gateway_lb, 1, 2 , 3, 4,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._address_txt, 2, 3 , 1, 2,
+ gtk.EXPAND|gtk.FILL, gtk.SHRINK)
+ table.attach(self._mask_txt, 2, 3, 2, 3,
+ gtk.EXPAND|gtk.FILL, gtk.SHRINK)
+ table.attach(self._gateway_txt, 2, 3 , 3, 4,
+ gtk.EXPAND|gtk.FILL, gtk.SHRINK)
+ table.attach(self._custom_add_cb, 3, 4 , 1, 2,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._custom_gate_cb, 3, 4 , 3, 4,
+ gtk.FILL, gtk.SHRINK)
+ self.show_all()
+ def _listen_signals(self):
+ self._rb_list = [self._dhcp_rb, self._custom_rb]
+ self._on_custom_enable = [self._address_lb,
+ self._address_txt,
+ self._mask_lb,
+ self._mask_txt,
+ self._gateway_lb,
+ self._gateway_txt]
+ self._on_custom_disable = [self._custom_add_cb,
+ self._custom_gate_cb]
+ self.set_rb_signal(self._rb_list,
+ self._custom_rb,
+ self._on_custom_enable,
+ self._on_custom_disable)
+ self._custom_gate_cb.connect("clicked", self._on_custom)
+ self._custom_add_cb.connect("clicked", self._on_custom)
+ def _insert_data(self, data):
if data.has_key("net_mode"):
- self.listen_signals()
if data["net_mode"] == "auto":
- self.get("dhcp_rb").set_active(True)
- self.set_manual_network(False)
+ self._dhcp_rb.set_active(True)
+ self._rb_callback(self._dhcp_rb,
+ {"is_custom":False,
+ "enable":self._on_custom_enable,
+ "disable":self._on_custom_disable})
if self.is_custom(data, "net_gateway"):
- self.get("custom_gateway").set_active(True)
+ self._custom_gate_cb.set_active(True)
if self.is_custom(data, "net_address"):
- self.get("custom_address").set_active(True)
+ self._custom_add_cb.set_active(True)
else:
- self.get("manual_rb").set_active(False)
- self.set_manual_network(True)
+ self._custom_rb.set_active(False)
self.if_available_set(data, "net_address",
- self.get("address").set_text)
+ self._address_txt.set_text)
self.if_available_set(data, "net_mask",
- self.get("networkmask").set_text)
+ self._mask_txt.set_text)
self.if_available_set(data, "net_gateway",
- self.get("gateway").set_text)
+ self._gateway_txt.set_text)
+ def _on_custom(self, widget):
+ if widget is self._custom_add_cb:
+ widgets = self._on_custom_enable[0:4]
+ else:
+ widgets = self._on_custom_enable[4:]
+ for x in widgets:
+ x.set_sensitive(widget.get_active())
+ def _rb_callback(self, widget, data):
+ EditWindowFrame._rb_callback(self, widget, data)
+ if not data["is_custom"]:
+ if self._custom_add_cb.get_active():
+ for x in data["enable"][0:4]:
+ x.set_sensitive(True)
+ if self._custom_gate_cb.get_active():
+ for x in data["enable"][4:]:
+ x.set_sensitive(True)
def is_custom(self, data, key):
if data.has_key(key):
if data[key] != "":
return True
return False
def collect_data(self, data):
- super(NetworkSettingsSection, self).collect_data(data)
data["net_mode"] = u"auto"
data["net_address"] = u""
data["net_mask"] = u""
data["net_gateway"] = u""
- if self.get("manual_rb").get_active():
+ if self._custom_rb.get_active():
data["net_mode"] = u"manual"
- if self.get("address").state == gtk.STATE_NORMAL:
- data["net_address"] = self.get_text_of("address")
- data["net_mask"] = self.get_text_of("networkmask")
- if self.get("gateway").state == gtk.STATE_NORMAL:
- data["net_gateway"] = self.get_text_of("gateway")
-
-class NameServerSection(EditSection):
- def __init__(self, parent):
- super(NameServerSection, self).__init__(parent)
- def set_custom_name(self, state):
- self.get("ns_custom_text").set_sensitive(state)
- def _on_type_changed(self, widget):
- if widget is self.get("ns_custom_rb"):
- self.set_custom_name(True)
- else:
- self.set_custom_name(False)
- def listen_signals(self):
- self.signal_connect("on_ns_default_rb_clicked",
- self._on_type_changed)
- self.signal_connect("on_ns_custom_rb_clicked",
- self._on_type_changed)
- self.signal_connect("on_ns_auto_rb_clicked",
- self._on_type_changed)
- def insert_data_and_show(self, data):
- self.listen_signals()
+ if self._address_txt.state == gtk.STATE_NORMAL:
+ data["net_address"] = self.get_text_of(self._address_txt)
+ data["net_mask"] = self.get_text_of(self._mask_txt)
+ if self._gateway_txt.state == gtk.STATE_NORMAL:
+ data["net_gateway"] = self.get_text_of(self._gateway_txt)
+
+class NameServerFrame(EditWindowFrame):
+ """Edit Window > Name Server Frame
+ """
+
+ def __init__(self, data):
+ EditWindowFrame.__init__(self, data)
+ def _create_ui(self):
+ self.set_label(_("<b>Name Servers</b>"))
+ self.get_label_widget().set_use_markup(True)
+
+ self._default_rb = gtk.RadioButton(label=_("Default"))
+
+ self._auto_rb = gtk.RadioButton(group=self._default_rb,
+ label=_("Automatic"))
+
+ self._custom_rb = gtk.RadioButton(group=self._default_rb,
+ label=_("Custom"))
+ self._custom_txt = gtk.Entry()
+
+ #structure
+ hbox = gtk.HBox(homogeneous=False,
+ spacing=5)
+ self.add(hbox)
+ hbox.pack_start(self._default_rb, expand=False)
+ hbox.pack_start(self._auto_rb, expand=False)
+ hbox.pack_start(self._custom_rb, expand=False)
+ hbox.pack_start(self._custom_txt, expand=True)
+ self.show_all()
+ def _listen_signals(self):
+ self.set_rb_signal(rb_list=[self._default_rb,
+ self._auto_rb,
+ self._custom_rb],
+ custom_rb=self._custom_rb,
+ on_custom_enable=[self._custom_txt])
+ def _insert_data(self, data):
if data.has_key("name_mode"):
+ self._custom_txt.set_sensitive(False)
if data["name_mode"] == "default":
- self.get("ns_default_rb").set_active(True)
- self.set_custom_name(False)
+ self._default_rb.set_active(True)
elif data["name_mode"] == "auto":
- self.get("ns_auto_rb").set_active(True)
- self.set_custom_name(False)
+ self._auto_rb.set_active(True)
elif data["name_mode"] == "custom":
- self.get("ns_custom_rb").set_active(True)
- self.set_custom_name(True)
+ self._custom_rb.set_active(True)
+ self._custom_txt.set_sensitive(True)
self.if_available_set(data, "name_server",
- self.get("ns_custom_text").set_text)
+ self._custom_txt.set_text)
def collect_data(self, data):
- super(NameServerSection, self).collect_data(data)
data["name_mode"] = u"default"
data["name_server"] = u""
- if self.get("ns_auto_rb").get_active():
+ if self._auto_rb.get_active():
data["name_mode"] = u"auto"
- if self.get("ns_custom_rb").get_active():
+ if self._custom_rb.get_active():
data["name_mode"] = u"custom"
- data["name_server"] = self.get_text_of("ns_custom_text")
-
-class WirelessSection(EditSection):
- def __init__(self, parent):
- super(WirelessSection, self).__init__(parent)
- self.iface = parent.iface
- self.package = parent._package
- self.connection = parent._connection
- self.is_new = parent.is_new
- # --- Password related
- def show_password(self, state):
- if not state:
- self.get("hidepass_cb").hide()
- self.get("pass_text").hide()
- self.get("pass_lb").hide()
- else:
- self.get("hidepass_cb").show()
- self.get("pass_text").show()
- self.get("pass_lb").show()
- def hide_password(self, widget):
- visibility = not widget.get_active()
- self.get("pass_text").set_visibility(visibility)
- # end Password related
- def scan(self, widget=None):
- self.get("scan_btn").hide()
- self.wifiitems.set_scanning(True)
- self.iface.scanRemote(self.device , self.package, self.wifilist)
- def security_types_changed(self, widget):
- index = widget.get_active()
- if index == 0:
- self.show_password(False)
- else:
- self.show_password(True)
- def listen_signals(self):
- self.signal_connect("on_security_types_changed",
- self.security_types_changed)
- self.signal_connect("on_hidepass_cb_toggled",
- self.hide_password)
- def set_security_types_style(self):
- ##Security Type ComboBox
- model = gtk.ListStore(str)
- security_types = self.get("security_types")
- security_types.set_model(model)
- cell = gtk.CellRendererText()
- security_types.pack_start(cell)
- security_types.add_attribute(cell,'text',0)
- def prepare_security_types(self, authType):
- self.set_security_types_style()
- noauth = _("No Authentication")
- self._authMethods = [("none", noauth)]
- append_to_types = self.get("security_types").append_text
- append_to_types(noauth)
- self.get("security_types").set_active(0)
- index = 1
- self.with_password = False
+ data["name_server"] = self.get_text_of(self._custom_txt)
+
+class WirelessFrame(EditWindowFrame):
+ """Edit Settings Window > WirelessFrame
+ """
+
+ def __init__(self, data, iface,
+ package=None,connection=None,
+ with_list=True, is_new=False):
+ self.iface = iface
+ self.package = package
+ self.connection = connection
+ self.with_list = with_list
+ self.is_new = is_new
+ EditWindowFrame.__init__(self, data)
+ def _create_ui(self):
+ self._essid_lb = gtk.Label(_("ESSID:"))
+ self._essid_lb.set_alignment(1.0, 0.5)
+
+ self._essid_txt = gtk.Entry()
+
+ self._security_lb = gtk.Label(_("Security Type:"))
+ self._security_lb.set_alignment(1.0, 0.5)
+
+ self._security_types = gtk.combo_box_new_text()
+ self._authMethods = [{"name":"none",
+ "desc":_("No Authentication")}]
+ self._security_types.append_text(self._authMethods[0]["desc"])
for name, desc in self.iface.authMethods(self.package):
- append_to_types(desc)
- self._authMethods.append((name, desc))
- if name == authType:
- self.get("security_types").set_active(index)
- self.with_password = True
- index += 1
- def on_wifi_clicked(self, widget, callback_data):
- data = callback_data["get_connection"]()
- self.get("essid_text").set_text(data["remote"])
- for index, method in enumerate(self._authMethods):
- if method[0] == data["encryption"]:
- self.get("security_types").set_active(index)
- def wifilist(self, package, exception, args):
- self.get("scan_btn").show()
- self.signal_connect("on_scan_btn_clicked",
- self.scan)
- if not exception:
- self.wifiitems.getConnections(args[0])
- self.wifiitems.listen_change(self.on_wifi_clicked)
+ self._authMethods.append({"name":name, "desc":desc})
+ self._security_types.append_text(desc)
+ self._set_current_security_type(_("No Authentication"))
+ self._pass_lb = gtk.Label(_("Password:"))
+ self._pass_lb.set_alignment(1.0, 0.5)
+
+ self._pass_txt = gtk.Entry()
+ self._pass_txt.set_visibility(False)
+
+ self._hide_cb = gtk.CheckButton(_("Hide Password"))
+ self._hide_cb.set_active(True)
+
+ if self.with_list:
+ table = gtk.Table(rows=4, columns=3)
+
+ self._wifiholder = WifiItemHolder()
+ self._scan_btn = gtk.Button("Scan")
+
+ table.attach(self._essid_lb, 1, 2, 0, 1,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._essid_txt, 2, 3, 0, 1,
+ gtk.EXPAND | gtk.FILL, gtk.SHRINK)
+ table.attach(self._security_lb, 1, 2, 1, 2,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._security_types, 2, 3, 1, 2,
+ gtk.EXPAND | gtk.FILL, gtk.SHRINK)
+ table.attach(self._pass_lb, 1, 2, 2, 3,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._pass_txt, 2, 3, 2, 3,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._hide_cb, 1, 3, 3, 4,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._wifiholder, 0, 1, 0, 3,
+ gtk.EXPAND | gtk.FILL, gtk.EXPAND | gtk.FILL)
+ table.attach(self._scan_btn, 0, 1, 3, 4,
+ gtk.FILL, gtk.SHRINK)
+ self._wifiholder.show()
else:
- print exception
- def insert_data_and_show(self, data, caps):
- self.listen_signals()
+ table = gtk.Table(rows=4, columns=2)
+
+ table.attach(self._essid_lb, 0, 1, 0, 1,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._essid_txt, 1, 2, 0, 1,
+ gtk.EXPAND | gtk.FILL, gtk.SHRINK)
+ table.attach(self._security_lb, 0, 1, 1, 2,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._security_types, 1, 2, 1, 2,
+ gtk.EXPAND | gtk.FILL, gtk.SHRINK)
+ table.attach(self._pass_lb, 0, 1, 2, 3,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._pass_txt, 1, 2, 2, 3,
+ gtk.FILL, gtk.SHRINK)
+ table.attach(self._hide_cb, 0, 2, 3, 4,
+ gtk.FILL, gtk.SHRINK)
+ self.add(table)
+ table.show()
+ self._essid_lb.show()
+ self._essid_txt.show()
+ self._security_lb.show()
+ self._security_types.show()
+ def _listen_signals(self):
+ self._hide_cb.connect("clicked", self._on_hide_pass)
+ self._security_types.connect("changed", self._on_sec_changed)
+ def _insert_data(self, data):
self.device = data["device_id"]
self.if_available_set(data, "remote",
- self.get("essid_text").set_text)
+ self._essid_txt.set_text)
+ caps = self.iface.capabilities(self.package)
modes = caps["modes"].split(",")
- if ("auth" in modes) and (not self.is_new):
- authType = self.iface.authType(self.package,
- self.connection)
- self.prepare_security_types(authType)
- self.get("hidepass_cb").set_active(True)
- if self.with_password:
+ if self.with_list:
+ self.scan()
+ if "auth" in modes:
+ if not self.is_new:
authType = self.iface.authType(self.package,
self.connection)
- authInfo = self.iface.authInfo(self.package,
+ self._set_current_security_type(authType)
+ self._show_password(False)
+ if (not authType == "none") & (not authType == ""):
+ info = self.iface.authInfo(self.package,
self.connection)
- authParams = self.iface.authParameters(self.package,
+ params = self.iface.authParameters(self.package,
authType)
- if len(authParams) == 1:
- password = authInfo.values()[0]
- self.get("pass_text").set_text(password)
- elif len(authParams) > 1:
- print "\nTODO:Dynamic WEP support"
- self.show_password(self.with_password)
- if self.is_new:
- pass
- self.wifiitems = WifiItemHolder()
- self.get("wireless_table").attach(self.wifiitems,
- 0, 1, 0, 3,
- gtk.EXPAND|gtk.FILL,
- gtk.EXPAND|gtk.FILL)
- self.scan()
+ if len(params) == 1:
+ password = info.values()[0]
+ self._pass_txt.set_text(password)
+ elif len(params) > 1:
+ print "\nTODO:Dynamic WEP Support"
+ self._show_password(True)
+ else:
+ self._security_types.set_active(0)
+ self._show_password(False)
+ def _on_hide_pass(self, widget):
+ self._pass_txt.set_visibility(not widget.get_active())
+ def _on_sec_changed(self, widget):
+ self._show_password(not widget.get_active() == 0)
+ def _show_password(self, state):
+ if not state:
+ self._hide_cb.hide()
+ self._pass_txt.hide()
+ self._pass_lb.hide()
+ else:
+ self._hide_cb.show()
+ self._pass_txt.show()
+ self._pass_lb.show()
+ def _get_current_security_type(self):
+ w = self._security_types
+ current = w.get_model()[w.get_active()][0]
+ for x in self._authMethods:
+ if x["desc"] == current:
+ return x["name"]
+ def _set_current_security_type(self, name):
+ for i, x in enumerate(self._authMethods):
+ if x["name"] == name:
+ self._security_types.set_active(i)
+ break
+ def scan(self, widget=None):
+ self._scan_btn.hide()
+ self._wifiholder.set_scanning(True)
+ self.iface.scanRemote(self.device ,
+ self.package,
+ self.listwifi)
+ def listwifi(self, package, exception, args):
+ self._scan_btn.show()
+ self._scan_btn.connect("clicked",
+ self.scan)
+ if not exception:
+ self._wifiholder.getConnections(args[0])
+ self._wifiholder.listen_change(self.on_wifi_clicked)
+ else:
+ print exception
+ def on_wifi_clicked(self, widget, callback_data):
+ data = callback_data["get_connection"]()
+ self._essid_txt.set_text(data["remote"])
+ self._set_current_security_type(data["encryption"])
def collect_data(self, data):
- super(WirelessSection, self).collect_data(data)
- data["remote"] = self.get_text_of("essid_text")
+ data["remote"] = self.get_text_of(self._essid_txt)
data["apmac"] = u"" #i think it is Access Point MAC
-
#Security
- data["auth"] = unicode(self._authMethods[
- self.get("security_types").get_active()][0])
+ data["auth"] = unicode(self._get_current_security_type())
if data["auth"] != u"none":
params = self.iface.authParameters("wireless_tools",
data["auth"])
if len(params) == 1:
key = "auth_%s" % params[0][0]
- data[key] = self.get_text_of("pass_text")
+ data[key] = self.get_text_of(self._pass_txt)
else:
print "TODO:Dynamic WEP Support"
-
-
-# end Edit Window Sections
-
-class EditInterface(object):
- """Imports edit window glade
- """
-
- def __init__(self,
- package,
- connection="",
- is_new=False,
- new_data={}):
- """init
- Arguments:
- - `package`:
- - `connection`:
- """
- bind_glade_domain()
- self.iface = NetworkIface()
- self._package = package
- self._connection = connection
- self._xml = glade.XML("ui/edit.glade")
- self.get = self._xml.get_widget
- self.listen_signals()
- self.is_new = is_new
- self.new_data = new_data
- self.insertData()
- def apply(self, widget):
- data = self.collect_data()
- try:
- self.iface.updateConnection(self._package,
- data["name"],
- data)
- except Exception, e:
- print "Exception:", unicode(e)
-
- if not self.name == data["name"]:
- self.iface.deleteConnection(self._package, self.name)
- if self.is_up:
- self.iface.connect(self._package, self.name)
- self.getWindow().destroy()
- def cancel(self, widget):
- self.getWindow().destroy()
- def listen_signals(self):
- self._xml.signal_connect("apply_btn_clicked",
- self.apply)
- self._xml.signal_connect("cancel_btn_clicked",
- self.cancel)
- def insertData(self):
- """show preferences
- """
- if not self.is_new:
- data = self.iface.info(self._package,
- self._connection)
- else:
- data = self.new_data
- self.name = data["name"]
- self.is_up = False
- if data.has_key("state"):
- if data["state"][0:2] == "up":
- self.is_up = True
- #Profile Frame
- self.profile_frame = ProfileSection(self)
- self.profile_frame.insert_data_and_show(data)
- #Network Settings Frame
- self.network_frame = NetworkSettingsSection(self)
- self.network_frame.insert_data_and_show(data)
- #Name Servers Frame
- self.name_frame = NameServerSection(self)
- self.name_frame.insert_data_and_show(data)
- # Wireless Frame
- if self._package == "wireless_tools":
- caps = self.iface.capabilities(self._package)
- self.wireless_frame = WirelessSection(self)
- self.wireless_frame.insert_data_and_show(data, caps)
- else:
- self.get("wireless_frame").hide()
-
- def collect_data(self):
- data = {}
- self.profile_frame.collect_data(data)
- self.network_frame.collect_data(data)
- self.name_frame.collect_data(data)
- if self._package == "wireless_tools":
- self.wireless_frame.collect_data(data)
- return data
- def getWindow(self):
- """returns window
- """
- return self.get("window_edit")
diff --git a/network_manager_gtk/windows.py b/network_manager_gtk/windows.py
index 726983f..7eb3486 100644
--- a/network_manager_gtk/windows.py
+++ b/network_manager_gtk/windows.py
@@ -1,139 +1,274 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Network Manager gtk windows module
MainWindow - Main Window
EditWindow - Edit Settings Window
NewWindow - New Profile Window
NewEditWindow - heyya
"""
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import gtk
from network_manager_gtk.translation import _
from network_manager_gtk.widgets import ProfilesHolder
-class MainWindow(gtk.Window):
- """Main Window
- profile list
+from network_manager_gtk.widgets import ProfileFrame
+from network_manager_gtk.widgets import NetworkFrame
+from network_manager_gtk.widgets import NameServerFrame
+from network_manager_gtk.widgets import WirelessFrame
+
+class BaseWindow(gtk.Window):
+ """BaseWindow for network_manager_gtk
"""
def __init__(self, iface):
- """init MainWindow
+ """init
Arguments:
- - `iface`: backend.NetworkIface
+ - `iface`:
"""
- gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
+ gtk.Window.__init__(self)
self.iface = iface
- self.get_state = lambda p,c:self.iface.info(p,c)[u"state"]
self._set_style()
self._create_ui()
self._listen_signals()
- self._get_profiles()
def _set_style(self):
- """sets title and defualt size
+ """sets title and default size etc.
"""
- self.set_title = _("Network Manager")
- self.set_default_size(400, 300)
+ pass
def _create_ui(self):
"""creates ui elements
"""
+ pass
+ def _listen_signals(self):
+ """listens signals
+ """
+ pass
+
+class MainWindow(BaseWindow):
+ """Main Window
+ profile list
+ """
+
+ def __init__(self, iface):
+ """init MainWindow
+
+ Arguments:
+ - `iface`: backend.NetworkIface
+ """
+ BaseWindow.__init__(self, iface)
+ self.get_state = lambda p,c:self.iface.info(p,c)[u"state"]
+ self._get_profiles()
+ def _set_style(self):
+ self.set_title(_("Network Manager"))
+ self.set_default_size(483, 300)
+ def _create_ui(self):
self._vbox = gtk.VBox()
self.add(self._vbox)
self._new_btn = gtk.Button(_('New Connection'))
self._vbox.pack_start(self._new_btn, expand=False)
self._holder = ProfilesHolder()
self._holder.set_connection_signal(self._connection_callback)
self._vbox.pack_start(self._holder)
def _connection_callback(self, widget, data):
"""listens ConnectionWidget's signals
Arguments:
- `widget`: widget
- `data`: {'action':(toggle | edit | delete)
'package':package_name,
'connection':connection_name}
"""
action = data["action"]
if action == "toggle":
self.iface.toggle(data["package"],
data["connection"])
elif action == "edit":
- pass
+ EditWindow(self.iface,
+ data["package"],
+ data["connection"]).show()
else:
m = _("Do you wanna delete the connection '%s' ?") % \
data['connection']
dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING,
buttons=gtk.BUTTONS_YES_NO,
message_format=m)
response = dialog.run()
if response == gtk.RESPONSE_YES:
try:
self.iface.deleteConnection(data['package'],
data['connection'])
except Exception, e:
print "Exception:",e
dialog.destroy()
def _listen_signals(self):
"""listen some signals
"""
+ self._new_btn.connect("clicked", self.new_profile)
self.connect("destroy", gtk.main_quit)
self.iface.listen(self._listen_comar)
+ def new_profile(self, widget):
+ EditWindow(self.iface,"wireless_tools", "new",
+ device_id=self.iface.devices("wireless_tools").keys()[0]).show()
def _listen_comar(self, package, signal, args):
"""comar listener
Arguments:
- `package`: package
- `signal`: signal type
- `args`: arguments
"""
args = map(lambda x: unicode(x), list(args))
if signal == "stateChanged":
self._holder.update_profile(package,
args[0],
args[1:])
elif signal == "deviceChanged":
print "TODO:Listen comar signal deviceChanged "
elif signal == "connectionChanged":
if args[0] == u"changed":
pass#Nothing to do ?
elif args[0] == u"added":
self._holder.add_profile(package,
args[1],
self.get_state(package,
args[1]))
elif args[0] == u"deleted":
self._holder.remove_profile(package,
args[1])
def _get_profiles(self):
"""get profiles from iface
"""
for package in self.iface.packages():
for connection in self.iface.connections(package):
state = self.get_state(package, connection)
self._holder.add_profile(package,
connection,
state)
+
+class EditWindow(BaseWindow):
+ """Edit Window
+ """
+
+ def __init__(self, iface, package, connection,
+ device_id=None):
+ """init
+
+ Arguments:
+ - `iface`: backend.NetworkIface
+ - `package`: package name
+ - `connection`: connection name (can be 'new')
+ """
+ self._package = package
+ self._connection = connection
+ self._device_id = device_id
+ self.is_wireless = False
+ if self._package == "wireless_tools":
+ self.is_wireless = True
+ BaseWindow.__init__(self, iface)
+ def _set_style(self):
+ """sets title and default size
+ """
+ self.set_title(_("Edit Connection"))
+ self.set_modal(True)
+ if self.is_wireless:
+ self.set_default_size(644, 400)
+ else:
+ self.set_default_size(483, 300)
+ def _create_ui(self):
+ self.data = ""
+ self._is_new = self._connection == "new"
+ if not self._is_new:
+ self.data = self.iface.info(self._package,
+ self._connection)
+ self.is_up = self.data["state"][0:2] == "up"
+ else:
+ dname = self.iface.devices(self._package)[self._device_id]
+ self.data = {"name":"",
+ "device_id":self._device_id,
+ "device_name":dname,
+ "net_mode":"auto",
+ "name_mode":"default"}
+ self.is_up = False
+ vbox = gtk.VBox(homogeneous=False,
+ spacing=6)
+ self.add(vbox)
+
+ self.pf = ProfileFrame(self.data)
+ vbox.pack_start(self.pf, expand=False, fill=False)
+
+ if self.is_wireless:
+ self.wf = WirelessFrame(self.data, self.iface,
+ package=self._package,
+ connection=self._connection,
+ with_list=True,
+ is_new=self._is_new)
+ vbox.pack_start(self.wf, expand=True, fill=True)
+ self.wf.show()
+
+ self.nf = NetworkFrame(self.data)
+ vbox.pack_start(self.nf, expand=False, fill=False)
+
+ self.nsf = NameServerFrame(self.data)
+ vbox.pack_start(self.nsf, expand=False, fill=False)
+ self.nsf.show()
+
+ buttons = gtk.HBox(homogeneous=False,
+ spacing=6)
+ self.apply_btn = gtk.Button(_("Apply"))
+ self.cancel_btn = gtk.Button(_("Cancel"))
+ buttons.pack_end(self.apply_btn, expand=False, fill=False)
+ buttons.pack_end(self.cancel_btn, expand=False, fill=False)
+ buttons.show_all()
+ vbox.pack_end(buttons, expand=False, fill=False)
+ vbox.show()
+ def _listen_signals(self):
+ self.apply_btn.connect("clicked", self.apply)
+ self.cancel_btn.connect("clicked", self.cancel)
+ def cancel(self, widget):
+ self.destroy()
+ def apply(self, widget):
+ data = self.collect_data()
+ try:
+ self.iface.updateConnection(self._package,
+ data["name"],
+ data)
+ except Exception, e:
+ print "Exception:", unicode(e)
+ if not self._is_new:
+ if not self.data["name"] == data["name"]:
+ self.iface.deleteConnection(self._package,
+ self.data["name"])
+ if self.is_up:
+ self.iface.connect(self._package, data["name"])
+ self.destroy()
+ def collect_data(self):
+ data = {}
+ self.pf.collect_data(data)
+ self.nf.collect_data(data)
+ self.nsf.collect_data(data)
+ if self.is_wireless: self.wf.collect_data(data)
+ return data
diff --git a/ui/edit.glade b/ui/edit.glade
deleted file mode 100644
index 7166e11..0000000
--- a/ui/edit.glade
+++ /dev/null
@@ -1,570 +0,0 @@
-<?xml version="1.0"?>
-<glade-interface>
- <!-- interface-requires gtk+ 2.16 -->
- <!-- interface-naming-policy project-wide -->
- <widget class="GtkWindow" id="window_edit">
- <property name="title" translatable="yes" comments="Edit Cable Settings Window Title">Edit Connection</property>
- <property name="default_width">640</property>
- <child>
- <widget class="GtkVBox" id="vbox1">
- <property name="visible">True</property>
- <property name="orientation">vertical</property>
- <property name="spacing">6</property>
- <child>
- <widget class="GtkFrame" id="profile_frame">
- <property name="visible">True</property>
- <property name="label_xalign">0</property>
- <property name="shadow_type">none</property>
- <child>
- <widget class="GtkAlignment" id="alignment1">
- <property name="visible">True</property>
- <property name="left_padding">12</property>
- <child>
- <widget class="GtkHBox" id="hbox1">
- <property name="visible">True</property>
- <property name="spacing">2</property>
- <child>
- <widget class="GtkLabel" id="label3">
- <property name="visible">True</property>
- <property name="label" translatable="yes">Profile Name:</property>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="position">0</property>
- </packing>
- </child>
- <child>
- <widget class="GtkEntry" id="profilename">
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="invisible_char">●</property>
- </widget>
- <packing>
- <property name="position">1</property>
- </packing>
- </child>
- <child>
- <widget class="GtkLabel" id="device_name_label">
- <property name="visible">True</property>
- <property name="xalign">0</property>
- <property name="label">device name goes here </property>
- <property name="use_markup">True</property>
- <property name="ellipsize">middle</property>
- </widget>
- <packing>
- <property name="pack_type">end</property>
- <property name="position">2</property>
- </packing>
- </child>
- </widget>
- </child>
- </widget>
- </child>
- <child>
- <widget class="GtkLabel" id="label1">
- <property name="visible">True</property>
- <property name="label" translatable="yes"><b>Profile</b></property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="type">label_item</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="position">0</property>
- </packing>
- </child>
- <child>
- <widget class="GtkFrame" id="wireless_frame">
- <property name="visible">True</property>
- <property name="label_xalign">0</property>
- <property name="shadow_type">none</property>
- <child>
- <widget class="GtkAlignment" id="alignment4">
- <property name="visible">True</property>
- <property name="left_padding">12</property>
- <child>
- <widget class="GtkTable" id="wireless_table">
- <property name="visible">True</property>
- <property name="n_rows">4</property>
- <property name="n_columns">3</property>
- <child>
- <widget class="GtkButton" id="scan_btn">
- <property name="label" translatable="yes">Scan</property>
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">True</property>
- <signal name="clicked" handler="on_scan_btn_clicked"/>
- </widget>
- <packing>
- <property name="top_attach">3</property>
- <property name="bottom_attach">4</property>
- <property name="y_options"></property>
- </packing>
- </child>
- <child>
- <widget class="GtkLabel" id="label9">
- <property name="visible">True</property>
- <property name="xalign">1</property>
- <property name="label" translatable="yes">Security Type:</property>
- </widget>
- <packing>
- <property name="left_attach">1</property>
- <property name="right_attach">2</property>
- <property name="top_attach">1</property>
- <property name="bottom_attach">2</property>
- <property name="x_options">GTK_FILL</property>
- <property name="y_options"></property>
- </packing>
- </child>
- <child>
- <widget class="GtkLabel" id="pass_lb">
- <property name="visible">True</property>
- <property name="xalign">1</property>
- <property name="label" translatable="yes">Password:</property>
- </widget>
- <packing>
- <property name="left_attach">1</property>
- <property name="right_attach">2</property>
- <property name="top_attach">2</property>
- <property name="bottom_attach">3</property>
- <property name="x_options">GTK_FILL</property>
- <property name="y_options">GTK_FILL</property>
- </packing>
- </child>
- <child>
- <widget class="GtkComboBox" id="security_types">
- <property name="visible">True</property>
- <signal name="changed" handler="on_security_types_changed"/>
- </widget>
- <packing>
- <property name="left_attach">2</property>
- <property name="right_attach">3</property>
- <property name="top_attach">1</property>
- <property name="bottom_attach">2</property>
- <property name="y_options"></property>
- </packing>
- </child>
- <child>
- <widget class="GtkEntry" id="pass_text">
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="invisible_char">●</property>
- <property name="invisible_char_set">True</property>
- </widget>
- <packing>
- <property name="left_attach">2</property>
- <property name="right_attach">3</property>
- <property name="top_attach">2</property>
- <property name="bottom_attach">3</property>
- <property name="y_options"></property>
- </packing>
- </child>
- <child>
- <widget class="GtkCheckButton" id="hidepass_cb">
- <property name="label" translatable="yes">Hide Password</property>
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">False</property>
- <property name="draw_indicator">True</property>
- <signal name="toggled" handler="on_hidepass_cb_toggled"/>
- </widget>
- <packing>
- <property name="left_attach">1</property>
- <property name="right_attach">3</property>
- <property name="top_attach">3</property>
- <property name="bottom_attach">4</property>
- <property name="x_options"></property>
- <property name="y_options"></property>
- </packing>
- </child>
- <child>
- <widget class="GtkLabel" id="label5">
- <property name="visible">True</property>
- <property name="xalign">1</property>
- <property name="label" translatable="yes">ESSID:</property>
- </widget>
- <packing>
- <property name="left_attach">1</property>
- <property name="right_attach">2</property>
- <property name="x_options">GTK_FILL</property>
- <property name="y_options"></property>
- </packing>
- </child>
- <child>
- <widget class="GtkEntry" id="essid_text">
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="invisible_char">●</property>
- </widget>
- <packing>
- <property name="left_attach">2</property>
- <property name="right_attach">3</property>
- <property name="x_options">GTK_FILL</property>
- <property name="y_options"></property>
- </packing>
- </child>
- <child>
- <placeholder/>
- </child>
- <child>
- <placeholder/>
- </child>
- <child>
- <placeholder/>
- </child>
- </widget>
- </child>
- </widget>
- </child>
- <child>
- <widget class="GtkLabel" id="label8">
- <property name="visible">True</property>
- <property name="label" translatable="yes"><b>Wireless</b></property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="type">label_item</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="position">1</property>
- </packing>
- </child>
- <child>
- <widget class="GtkFrame" id="network_frame">
- <property name="visible">True</property>
- <property name="label_xalign">0</property>
- <property name="shadow_type">none</property>
- <child>
- <widget class="GtkAlignment" id="alignment2">
- <property name="visible">True</property>
- <property name="left_padding">12</property>
- <child>
- <widget class="GtkVBox" id="vbox2">
- <property name="visible">True</property>
- <property name="orientation">vertical</property>
- <property name="spacing">5</property>
- <child>
- <widget class="GtkRadioButton" id="dhcp_rb">
- <property name="label" translatable="yes">Use DHCP</property>
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">False</property>
- <property name="active">True</property>
- <property name="draw_indicator">True</property>
- <signal name="clicked" handler="on_dhcp_rb_clicked"/>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="position">0</property>
- </packing>
- </child>
- <child>
- <widget class="GtkTable" id="table2">
- <property name="visible">True</property>
- <property name="n_rows">3</property>
- <property name="n_columns">4</property>
- <property name="row_spacing">5</property>
- <child>
- <widget class="GtkRadioButton" id="manual_rb">
- <property name="label" translatable="yes">Use Manual Settings</property>
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">False</property>
- <property name="active">True</property>
- <property name="draw_indicator">True</property>
- <property name="group">dhcp_rb</property>
- <signal name="clicked" handler="on_manual_rb_clicked"/>
- </widget>
- </child>
- <child>
- <widget class="GtkLabel" id="address_lb">
- <property name="visible">True</property>
- <property name="xalign">1</property>
- <property name="label" translatable="yes">Address:</property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="left_attach">1</property>
- <property name="right_attach">2</property>
- <property name="x_options">GTK_FILL</property>
- <property name="y_options"></property>
- </packing>
- </child>
- <child>
- <widget class="GtkLabel" id="networkmask_lb">
- <property name="visible">True</property>
- <property name="xalign">1</property>
- <property name="label" translatable="yes">Network Mask:</property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="left_attach">1</property>
- <property name="right_attach">2</property>
- <property name="top_attach">1</property>
- <property name="bottom_attach">2</property>
- <property name="x_options">GTK_FILL</property>
- <property name="y_options"></property>
- </packing>
- </child>
- <child>
- <widget class="GtkLabel" id="gateway_lb">
- <property name="visible">True</property>
- <property name="xalign">1</property>
- <property name="label" translatable="yes">Default Gateway:</property>
- </widget>
- <packing>
- <property name="left_attach">1</property>
- <property name="right_attach">2</property>
- <property name="top_attach">2</property>
- <property name="bottom_attach">3</property>
- <property name="y_options">GTK_EXPAND</property>
- </packing>
- </child>
- <child>
- <widget class="GtkEntry" id="address">
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="invisible_char">●</property>
- </widget>
- <packing>
- <property name="left_attach">2</property>
- <property name="right_attach">3</property>
- </packing>
- </child>
- <child>
- <widget class="GtkEntry" id="networkmask">
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="invisible_char">●</property>
- </widget>
- <packing>
- <property name="left_attach">2</property>
- <property name="right_attach">3</property>
- <property name="top_attach">1</property>
- <property name="bottom_attach">2</property>
- </packing>
- </child>
- <child>
- <widget class="GtkEntry" id="gateway">
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="invisible_char">●</property>
- </widget>
- <packing>
- <property name="left_attach">2</property>
- <property name="right_attach">3</property>
- <property name="top_attach">2</property>
- <property name="bottom_attach">3</property>
- </packing>
- </child>
- <child>
- <widget class="GtkCheckButton" id="custom_address">
- <property name="label" translatable="yes">Custom</property>
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">False</property>
- <property name="draw_indicator">True</property>
- <signal name="toggled" handler="on_custom_address_toggled"/>
- </widget>
- <packing>
- <property name="left_attach">3</property>
- <property name="right_attach">4</property>
- </packing>
- </child>
- <child>
- <widget class="GtkCheckButton" id="custom_gateway">
- <property name="label" translatable="yes">Custom</property>
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">False</property>
- <property name="draw_indicator">True</property>
- <signal name="toggled" handler="on_custom_gateway_toggled"/>
- </widget>
- <packing>
- <property name="left_attach">3</property>
- <property name="right_attach">4</property>
- <property name="top_attach">2</property>
- <property name="bottom_attach">3</property>
- </packing>
- </child>
- <child>
- <placeholder/>
- </child>
- <child>
- <placeholder/>
- </child>
- <child>
- <placeholder/>
- </child>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- </child>
- </widget>
- </child>
- <child>
- <widget class="GtkLabel" id="label2">
- <property name="visible">True</property>
- <property name="label" translatable="yes"><b>Network Settings</b></property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="type">label_item</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="position">2</property>
- </packing>
- </child>
- <child>
- <widget class="GtkFrame" id="ns_frame">
- <property name="visible">True</property>
- <property name="label_xalign">0</property>
- <property name="shadow_type">none</property>
- <child>
- <widget class="GtkAlignment" id="alignment3">
- <property name="visible">True</property>
- <property name="left_padding">12</property>
- <child>
- <widget class="GtkHBox" id="hbox2">
- <property name="visible">True</property>
- <property name="spacing">5</property>
- <child>
- <widget class="GtkRadioButton" id="ns_default_rb">
- <property name="label" translatable="yes">Default</property>
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">False</property>
- <property name="active">True</property>
- <property name="draw_indicator">True</property>
- <signal name="clicked" handler="on_ns_default_rb_clicked"/>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="position">0</property>
- </packing>
- </child>
- <child>
- <widget class="GtkRadioButton" id="ns_auto_rb">
- <property name="label" translatable="yes">Automatic</property>
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">False</property>
- <property name="active">True</property>
- <property name="draw_indicator">True</property>
- <property name="group">ns_default_rb</property>
- <signal name="clicked" handler="on_ns_auto_rb_clicked"/>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="position">1</property>
- </packing>
- </child>
- <child>
- <widget class="GtkRadioButton" id="ns_custom_rb">
- <property name="label" translatable="yes">Custom</property>
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">False</property>
- <property name="draw_indicator">True</property>
- <property name="group">ns_default_rb</property>
- <signal name="clicked" handler="on_ns_custom_rb_clicked"/>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="position">2</property>
- </packing>
- </child>
- <child>
- <widget class="GtkEntry" id="ns_custom_text">
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="editable">False</property>
- <property name="invisible_char">●</property>
- </widget>
- <packing>
- <property name="position">3</property>
- </packing>
- </child>
- </widget>
- </child>
- </widget>
- </child>
- <child>
- <widget class="GtkLabel" id="label4">
- <property name="visible">True</property>
- <property name="label" translatable="yes"><b>Name Servers</b></property>
- <property name="use_markup">True</property>
- </widget>
- <packing>
- <property name="type">label_item</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="position">3</property>
- </packing>
- </child>
- <child>
- <widget class="GtkHBox" id="hbox3">
- <property name="visible">True</property>
- <property name="spacing">5</property>
- <child>
- <widget class="GtkButton" id="cancel_btn">
- <property name="label" translatable="yes">Cancel</property>
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">True</property>
- <property name="use_underline">True</property>
- <signal name="clicked" handler="cancel_btn_clicked"/>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="pack_type">end</property>
- <property name="position">1</property>
- </packing>
- </child>
- <child>
- <widget class="GtkButton" id="apply_btn">
- <property name="label" translatable="yes">Apply</property>
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">True</property>
- <property name="use_underline">True</property>
- <signal name="clicked" handler="apply_btn_clicked"/>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="pack_type">end</property>
- <property name="position">0</property>
- </packing>
- </child>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="pack_type">end</property>
- <property name="position">4</property>
- </packing>
- </child>
- </widget>
- </child>
- </widget>
-</glade-interface>
diff --git a/ui/main.glade b/ui/main.glade
deleted file mode 100644
index 94d4120..0000000
--- a/ui/main.glade
+++ /dev/null
@@ -1,59 +0,0 @@
-<?xml version="1.0"?>
-<glade-interface>
- <!-- interface-requires gtk+ 2.16 -->
- <!-- interface-naming-policy project-wide -->
- <widget class="GtkWindow" id="window_main">
- <property name="title" translatable="yes" comments="Main Window Title">Network Manager</property>
- <property name="window_position">center</property>
- <property name="default_width">300</property>
- <signal name="destroy" handler="on_window_main_destroy"/>
- <child>
- <widget class="GtkVBox" id="vbox1">
- <property name="visible">True</property>
- <property name="orientation">vertical</property>
- <child>
- <widget class="GtkHBox" id="hbox1">
- <property name="visible">True</property>
- <child>
- <widget class="GtkButton" id="new">
- <property name="label" translatable="yes">New Connection</property>
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">True</property>
- <signal name="clicked" handler="on_new_clicked"/>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="position">0</property>
- </packing>
- </child>
- <child>
- <placeholder/>
- </child>
- </widget>
- <packing>
- <property name="expand">False</property>
- <property name="fill">False</property>
- <property name="position">0</property>
- </packing>
- </child>
- <child>
- <widget class="GtkScrolledWindow" id="holder">
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="hscrollbar_policy">automatic</property>
- <property name="vscrollbar_policy">automatic</property>
- <property name="shadow_type">in</property>
- <child>
- <placeholder/>
- </child>
- </widget>
- <packing>
- <property name="position">1</property>
- </packing>
- </child>
- </widget>
- </child>
- </widget>
-</glade-interface>
|
rdno/pardus-network-manager-gtk
|
d527b5704f38b9ade11f1c1205e7f13b62dc73b1
|
added MainWindow
|
diff --git a/network-manager-gtk.py b/network-manager-gtk.py
index 73a0d23..2fe57b4 100755
--- a/network-manager-gtk.py
+++ b/network-manager-gtk.py
@@ -1,131 +1,53 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import os
import pygtk
pygtk.require('2.0')
import gtk
-import gobject
from network_manager_gtk.backend import NetworkIface
-from network_manager_gtk.widgets import ConnectionWidget
-from network_manager_gtk.widgets import MainInterface
-from network_manager_gtk.widgets import EditInterface
+from network_manager_gtk.windows import MainWindow
-from network_manager_gtk.translation import _
class Base(object):
def __init__(self):
self._dbusMainLoop()
self.iface = NetworkIface()
- #ui
- self.main = MainInterface()
- self.window = self.main.getWindow()
- # show connection as Widgets
- self.widgets = {}
- self.showConnections()
- self.holder = self.main.getHolder()
- self.holder.add_with_viewport(self.vbox)
- # listen for changes
- self.iface.listen(self._listener)
-
- def _onConnectionClicked(self, widget, callback_data):
- self.iface.toggle(callback_data['package'],
- callback_data['connection'])
- def _onConnectionEdit(self, widget, callback_data):
- try:
- a = EditInterface(callback_data['package'],
- callback_data['connection'])
- a.getWindow().props.modal = True
- a.getWindow().show()
- except Exception, e:
- print "Exception:", e
- def _onConnectionDelete(self, widget, callback_data):
- m = _("Do you wanna delete the connection '%(name)s' ?") % \
- {"name":callback_data['connection']}
- dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING,
- buttons=gtk.BUTTONS_YES_NO,
- message_format=m)
- response = dialog.run()
- if response == gtk.RESPONSE_YES:
- try:
- self.iface.deleteConnection(callback_data['package'],
- callback_data['connection'])
- except Exception, e:
- print "Exception:",e
- dialog.destroy()
- def showConnections(self):
- """show connection on gui
- """
- self.vbox = gtk.VBox(homogeneous=False, spacing=10)
- for package in self.iface.packages():
- self.widgets[package] = {}
- for connection in self.iface.connections(package):
- self.add_to_vbox(package, connection)
- def add_to_vbox(self, package, connection):
- state = self.iface.info(package, connection)[u"state"]
- con_wg = ConnectionWidget(package,
- connection,
- state)
- con_wg.connectSignals(self._onConnectionClicked,
- self._onConnectionEdit,
- self._onConnectionDelete)
- self.vbox.pack_start(con_wg, expand=False, fill=False)
- self.widgets[package][connection] = con_wg
- def _listener(self, package, signal, args):
- """comar listener
- Arguments:
- - `package`: package of item
- - `signal`: comar signal type
- - `args`: arguments
- """
- args = map(lambda x: unicode(x), list(args))
- if signal == "stateChanged":
- self.widgets[package][args[0]].setMode(args[1:])
- elif signal == "deviceChanged":
- print "TODO:Listen comar signal deviceChanged "
- elif signal == "connectionChanged":
- if args[0] == u"changed":
- pass#Nothing to do ?
- elif args[0] == u"added":
- self.add_to_vbox(package, args[1])
- self.vbox.show_all()
- elif args[0] == u"deleted":
- self.vbox.remove(self.widgets[package][args[1]])
- pass
+ self.window = MainWindow(self.iface)
def _dbusMainLoop(self):
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default = True)
def run(self, argv=None):
"""Runs the program
Arguments:
- `argv`: sys.argv
"""
self.window.show_all()
gtk.main()
if __name__ == "__main__":
import sys
app = Base()
app.run(sys.argv)
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index ab98ac7..d343c0f 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,620 +1,671 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
"""A special widget contains connection related stuff
"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
- self._createUI()
- def _createUI(self):
+ self._create_ui()
+ def _create_ui(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
- self.setMode(self._state.split(' '))
- def setMode(self, args):
+ self.set_mode(self._state.split(' '))
+ def set_mode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- - `args`: state, detail
+ - `args`: [state, detail]
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
- self._info.set_markup('<span color="green">'+
- args[1]+
+ self._info.set_markup(states[args[0]]+':'+
+ '<span color="green">'+
+ args[1] +
'</span>')
- def connectSignals(self, click_signal, edit_signal, delete_signal):
+ def connect_signals(self, callback):
"""connect widgets signals
+ returns {'action':(toggle | edit | delete)
+ 'package':package_name,
+ 'connection':connection_name}
Arguments:
- - `click_signal`: toggle connection signal
- - `edit_signal`: edit signal
- - `delete_signal`: delete signal
+ - `callback`: callback function
"""
- self.check_btn.connect("pressed", click_signal,
- {"package":self._package_name,
+ self.check_btn.connect("pressed", callback,
+ {"action":"toggle",
+ "package":self._package_name,
"connection":self._connection_name})
- self.edit_btn.connect("clicked", edit_signal,
- {"package":self._package_name,
+ self.edit_btn.connect("clicked", callback,
+ {"action":"edit",
+ "package":self._package_name,
"connection":self._connection_name})
- self.delete_btn.connect("clicked", delete_signal,
- {"package":self._package_name,
+ self.delete_btn.connect("clicked", callback,
+ {"action":"delete",
+ "package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
+class ProfilesHolder(gtk.ScrolledWindow):
+ """Holds Profile List
+ """
+
+ def __init__(self):
+ """init
+ """
+ gtk.ScrolledWindow.__init__(self)
+ self.set_shadow_type(gtk.SHADOW_IN)
+ self.set_policy(gtk.POLICY_NEVER,
+ gtk.POLICY_AUTOMATIC)
+ self._vbox = gtk.VBox(homogeneous=False,
+ spacing=10)
+ self.add_with_viewport(self._vbox)
+ self._profiles = {}
+ def set_connection_signal(self, callback):
+ """sets default callback for ConnectionWidget
+ """
+ self._callback = callback
+ def add_profile(self, package, connection, state):
+ """add profiles to vbox
+ """
+ con_wg = ConnectionWidget(package,
+ connection,
+ state)
+ con_wg.connect_signals(self._callback)
+ self._vbox.pack_start(con_wg, expand=False, fill=False)
+ if not self._profiles.has_key(package):
+ self._profiles[package] = {}
+ self._profiles[package][connection] = {"state":state,
+ "widget":con_wg}
+ self._vbox.show_all()
+ def update_profile(self, package, connection, state):
+ """update connection state
+ """
+ c = self._profiles[package][connection]
+ c["state"] = state
+ c["widget"].set_mode(state)
+ def remove_profile(self, package, connection):
+ """remove profile
+ """
+ c = self._profiles[package][connection]
+ self._vbox.remove(c["widget"])
+
+gobject.type_register(ProfilesHolder)
+
class WifiItemHolder(gtk.ScrolledWindow):
"""holder for wifi connections
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
return data
return None
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
class NewWifiConnectionItem(gtk.Table):
"""new wifi connection
"""
def __init__(self,
device_id,
connection):
"""init
Arguments:
- `device_id`: connection device
- `connection`: scanRemote callback dict
example: {'remote':'ESSID Name',
'quality':'60',
'quality_max':'100'
'encryption':'wpa-psk',
...}
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._device_id = device_id
self._connection = connection;
self._create_ui();
def _create_ui(self):
"""creates UI
"""
frac = float(self._connection['quality'])/ \
float(self._connection['quality_max'])
per = self._connection['quality']
self._quality_bar = gtk.ProgressBar()
self._quality_bar.set_fraction(frac)
self._quality_bar.set_text(_("%d%%") % int(per))
self._name_txt = gtk.Label(self._connection['remote'])
self._name_txt.set_alignment(0.0 , 0.5)
self._encrypt_txt = gtk.Label(self._connection['encryption'])
self._encrypt_txt.set_alignment(0.0 , 0.5)
self._connect_btn = gtk.Button(_("Connect"))
self.attach(self._quality_bar, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._name_txt, 1, 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._encrypt_txt, 1, 2, 1, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._connect_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
gobject.type_register(NewWifiConnectionItem)
class NewConnectionWindow(gtk.Window):
"""show new connections as a list
"""
def __init__(self, iface):
"""init
Arguments:
- `iface`: NetworkIface
"""
gtk.Window.__init__(self)
self._iface = iface
self.set_title(_("New Connection"))
self._package = "wireless_tools"
self._devices = self._iface.devices(self._package).keys()
self._create_ui();
self._cons = [] #connections
self.scan()
def _create_ui(self):
"""creates ui
"""
self._ui = gtk.VBox()
self.add(self._ui)
self._refresh_btn = gtk.Button("")
self._refresh_btn.connect("clicked", self.scan)
self._ui.add(self._refresh_btn)
self._list= gtk.VBox()
self._ui.add(self._list)
def _set_scanning(self, status):
"""disable/enable refresh btn
Arguments:
- `status`: if True then disable button
"""
if status:
self._refresh_btn.set_label(_("Refreshing..."))
else:
self._refresh_btn.set_label(_("Refresh"))
self._refresh_btn.set_sensitive(not status)
def scan(self, widget=None):
"""scan for wifi networks
"""
self._set_scanning(True)
d = self._devices[0] #TODO:more than one device support
self._iface.scanRemote(d, self._package,
self._scan_callback)
def _scan_callback(self, package, exception, args):
"""wifi scan callback
Arguments:
- `package`: package name
- `exception`: exception
- `args`: connection array
"""
self._set_scanning(False)
if not exception:
self._show_list(args[0])
else:
print exception
def _show_list(self, connections):
"""show list
Arguments:
- `connections`: connections array
"""
d = self._devices[0]
#remove old ones
map(self._list.remove, self._cons)
self._cons = [NewWifiConnectionItem(d, x)
for x in connections]
#add new ones
map(self._list.add, self._cons)
self.show_all()
gobject.type_register(NewConnectionWindow)
class dummy_data_creator(object):
"""create
"""
def __init__(self,
device,
device_name,
essid=None):
"""init
Arguments:
- `device`:
- `essid`:
"""
self._wireless = False
self._device = device
self._device_name = device_name
if essid is not None:
self._essid = essid
self._wireless = True
def get(self):
"""get data
"""
data = {}
if self._wireless:
data["name"] = self._essid
else:
data["name"] = "Kablo" #TODO: what?
data["device_id"] = self._device
data["device_name"] = self._device_name
#Network Settings
data["net_mode"] = "auto"
data["net_address"] = ""
data["net_mask"] = ""
data["net_gateway"] = ""
#Name Server Settings
data["name_mode"] = "default"
data["name_server"] = ""
return data
class MainInterface(object):
"""Imports main window glade
"""
def __init__(self):
"""import glade
"""
bind_glade_domain()
self._xml = glade.XML("ui/main.glade")
self._xml.signal_connect("on_window_main_destroy",
gtk.main_quit)
self._xml.signal_connect("on_new_clicked",
self.show_news)
self._window = self._xml.get_widget("window_main")
self._holder = self._xml.get_widget("holder")
self.iface = NetworkIface()
def show_news(self, widget):
a = NewConnectionWindow(self.iface)
a.show()
def brand_new(self, widget):
"""deneme
Arguments:
- `widget`:
"""
pack = "net_tools"
device = self.iface.devices(pack).keys()[0]
name = self.iface.devices(pack)[device]
a = EditInterface(pack,
"",
is_new=True,
new_data=dummy_data_creator(device, name).get())
a.getWindow().show()
def getWindow(self):
"""returns window
"""
return self._window
def getHolder(self):
"""returns holder
"""
return self._holder
# --- Edit Window Sections (in ui: frame)
class EditSection(object):
def __init__(self, parent):
super(EditSection, self).__init__()
self.get = parent.get
self.signal_connect = parent._xml.signal_connect
self.parent = parent
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
def get_text_of(self, name):
"""gets text from widget in unicode"""
return unicode(self.get(name).get_text())
def collect_data(self, data):
"""collect data from ui and append datas to
given(data) dictionary"""
pass
class ProfileSection(EditSection):
def __init__(self, parent):
super(ProfileSection, self).__init__(parent)
def insert_data_and_show(self, data):
self.if_available_set(data, "name",
self.get("profilename").set_text)
self.if_available_set(data, "device_name",
self.get("device_name_label").set_text)
self.device_id = data["device_id"]
#TODO:more than one device support
def collect_data(self, data):
super(ProfileSection, self).collect_data(data)
data["name"] = self.get_text_of("profilename")
data["device_id"] = unicode(self.device_id)
class NetworkSettingsSection(EditSection):
def __init__(self, parent):
super(NetworkSettingsSection, self).__init__(parent)
def _on_type_changed(self, widget):
if widget is self.get("dhcp_rb"):
self.set_manual_network(False)
else:
self.set_manual_network(True)
def set_manual_network(self, state):
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
# custom things
self.get("custom_gateway").set_sensitive(not state)
self.get("custom_address").set_sensitive(not state)
if not state:
self._on_custom_address(self.get("custom_address"))
self._on_custom_gateway(self.get("custom_gateway"))
def _on_custom_address(self, widget):
state = widget.get_active()
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
def _on_custom_gateway(self, widget):
state = widget.get_active()
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
def listen_signals(self):
self.signal_connect("on_dhcp_rb_clicked",
self._on_type_changed)
self.signal_connect("on_manual_rb_clicked",
self._on_type_changed)
self.signal_connect("on_custom_gateway_toggled",
self._on_custom_gateway)
self.signal_connect("on_custom_address_toggled",
self._on_custom_address)
def insert_data_and_show(self, data):
if data.has_key("net_mode"):
self.listen_signals()
if data["net_mode"] == "auto":
self.get("dhcp_rb").set_active(True)
self.set_manual_network(False)
if self.is_custom(data, "net_gateway"):
self.get("custom_gateway").set_active(True)
if self.is_custom(data, "net_address"):
self.get("custom_address").set_active(True)
else:
self.get("manual_rb").set_active(False)
self.set_manual_network(True)
self.if_available_set(data, "net_address",
self.get("address").set_text)
self.if_available_set(data, "net_mask",
self.get("networkmask").set_text)
self.if_available_set(data, "net_gateway",
self.get("gateway").set_text)
def is_custom(self, data, key):
if data.has_key(key):
if data[key] != "":
return True
return False
def collect_data(self, data):
super(NetworkSettingsSection, self).collect_data(data)
data["net_mode"] = u"auto"
data["net_address"] = u""
data["net_mask"] = u""
data["net_gateway"] = u""
if self.get("manual_rb").get_active():
data["net_mode"] = u"manual"
if self.get("address").state == gtk.STATE_NORMAL:
data["net_address"] = self.get_text_of("address")
data["net_mask"] = self.get_text_of("networkmask")
if self.get("gateway").state == gtk.STATE_NORMAL:
data["net_gateway"] = self.get_text_of("gateway")
class NameServerSection(EditSection):
def __init__(self, parent):
super(NameServerSection, self).__init__(parent)
def set_custom_name(self, state):
self.get("ns_custom_text").set_sensitive(state)
def _on_type_changed(self, widget):
if widget is self.get("ns_custom_rb"):
self.set_custom_name(True)
else:
self.set_custom_name(False)
def listen_signals(self):
self.signal_connect("on_ns_default_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_custom_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_auto_rb_clicked",
self._on_type_changed)
def insert_data_and_show(self, data):
self.listen_signals()
if data.has_key("name_mode"):
if data["name_mode"] == "default":
self.get("ns_default_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "auto":
self.get("ns_auto_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "custom":
self.get("ns_custom_rb").set_active(True)
self.set_custom_name(True)
self.if_available_set(data, "name_server",
self.get("ns_custom_text").set_text)
def collect_data(self, data):
super(NameServerSection, self).collect_data(data)
data["name_mode"] = u"default"
data["name_server"] = u""
if self.get("ns_auto_rb").get_active():
data["name_mode"] = u"auto"
if self.get("ns_custom_rb").get_active():
data["name_mode"] = u"custom"
data["name_server"] = self.get_text_of("ns_custom_text")
class WirelessSection(EditSection):
def __init__(self, parent):
super(WirelessSection, self).__init__(parent)
self.iface = parent.iface
self.package = parent._package
self.connection = parent._connection
self.is_new = parent.is_new
# --- Password related
def show_password(self, state):
if not state:
self.get("hidepass_cb").hide()
self.get("pass_text").hide()
self.get("pass_lb").hide()
else:
self.get("hidepass_cb").show()
self.get("pass_text").show()
self.get("pass_lb").show()
def hide_password(self, widget):
visibility = not widget.get_active()
self.get("pass_text").set_visibility(visibility)
# end Password related
def scan(self, widget=None):
self.get("scan_btn").hide()
self.wifiitems.set_scanning(True)
self.iface.scanRemote(self.device , self.package, self.wifilist)
def security_types_changed(self, widget):
index = widget.get_active()
if index == 0:
self.show_password(False)
else:
self.show_password(True)
def listen_signals(self):
self.signal_connect("on_security_types_changed",
self.security_types_changed)
self.signal_connect("on_hidepass_cb_toggled",
self.hide_password)
def set_security_types_style(self):
##Security Type ComboBox
model = gtk.ListStore(str)
security_types = self.get("security_types")
security_types.set_model(model)
cell = gtk.CellRendererText()
security_types.pack_start(cell)
security_types.add_attribute(cell,'text',0)
def prepare_security_types(self, authType):
self.set_security_types_style()
noauth = _("No Authentication")
self._authMethods = [("none", noauth)]
append_to_types = self.get("security_types").append_text
append_to_types(noauth)
self.get("security_types").set_active(0)
index = 1
self.with_password = False
for name, desc in self.iface.authMethods(self.package):
append_to_types(desc)
self._authMethods.append((name, desc))
if name == authType:
self.get("security_types").set_active(index)
self.with_password = True
index += 1
def on_wifi_clicked(self, widget, callback_data):
data = callback_data["get_connection"]()
self.get("essid_text").set_text(data["remote"])
for index, method in enumerate(self._authMethods):
if method[0] == data["encryption"]:
self.get("security_types").set_active(index)
def wifilist(self, package, exception, args):
self.get("scan_btn").show()
self.signal_connect("on_scan_btn_clicked",
self.scan)
if not exception:
self.wifiitems.getConnections(args[0])
self.wifiitems.listen_change(self.on_wifi_clicked)
else:
print exception
def insert_data_and_show(self, data, caps):
self.listen_signals()
self.device = data["device_id"]
self.if_available_set(data, "remote",
self.get("essid_text").set_text)
modes = caps["modes"].split(",")
if ("auth" in modes) and (not self.is_new):
authType = self.iface.authType(self.package,
self.connection)
self.prepare_security_types(authType)
self.get("hidepass_cb").set_active(True)
if self.with_password:
authType = self.iface.authType(self.package,
self.connection)
authInfo = self.iface.authInfo(self.package,
self.connection)
authParams = self.iface.authParameters(self.package,
authType)
if len(authParams) == 1:
password = authInfo.values()[0]
self.get("pass_text").set_text(password)
elif len(authParams) > 1:
diff --git a/network_manager_gtk/windows.py b/network_manager_gtk/windows.py
new file mode 100644
index 0000000..726983f
--- /dev/null
+++ b/network_manager_gtk/windows.py
@@ -0,0 +1,139 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+"""Network Manager gtk windows module
+
+MainWindow - Main Window
+EditWindow - Edit Settings Window
+NewWindow - New Profile Window
+NewEditWindow - heyya
+
+"""
+
+#
+# Rıdvan Ãrsvuran (C) 2009
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+
+import gtk
+
+from network_manager_gtk.translation import _
+
+from network_manager_gtk.widgets import ProfilesHolder
+
+class MainWindow(gtk.Window):
+ """Main Window
+ profile list
+ """
+
+ def __init__(self, iface):
+ """init MainWindow
+
+ Arguments:
+ - `iface`: backend.NetworkIface
+ """
+ gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
+ self.iface = iface
+ self.get_state = lambda p,c:self.iface.info(p,c)[u"state"]
+ self._set_style()
+ self._create_ui()
+ self._listen_signals()
+ self._get_profiles()
+ def _set_style(self):
+ """sets title and defualt size
+ """
+ self.set_title = _("Network Manager")
+ self.set_default_size(400, 300)
+ def _create_ui(self):
+ """creates ui elements
+ """
+ self._vbox = gtk.VBox()
+ self.add(self._vbox)
+
+ self._new_btn = gtk.Button(_('New Connection'))
+ self._vbox.pack_start(self._new_btn, expand=False)
+
+ self._holder = ProfilesHolder()
+ self._holder.set_connection_signal(self._connection_callback)
+ self._vbox.pack_start(self._holder)
+ def _connection_callback(self, widget, data):
+ """listens ConnectionWidget's signals
+
+ Arguments:
+ - `widget`: widget
+ - `data`: {'action':(toggle | edit | delete)
+ 'package':package_name,
+ 'connection':connection_name}
+ """
+ action = data["action"]
+ if action == "toggle":
+ self.iface.toggle(data["package"],
+ data["connection"])
+ elif action == "edit":
+ pass
+ else:
+ m = _("Do you wanna delete the connection '%s' ?") % \
+ data['connection']
+ dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING,
+ buttons=gtk.BUTTONS_YES_NO,
+ message_format=m)
+ response = dialog.run()
+ if response == gtk.RESPONSE_YES:
+ try:
+ self.iface.deleteConnection(data['package'],
+ data['connection'])
+ except Exception, e:
+ print "Exception:",e
+ dialog.destroy()
+ def _listen_signals(self):
+ """listen some signals
+ """
+ self.connect("destroy", gtk.main_quit)
+ self.iface.listen(self._listen_comar)
+ def _listen_comar(self, package, signal, args):
+ """comar listener
+
+ Arguments:
+ - `package`: package
+ - `signal`: signal type
+ - `args`: arguments
+ """
+ args = map(lambda x: unicode(x), list(args))
+ if signal == "stateChanged":
+ self._holder.update_profile(package,
+ args[0],
+ args[1:])
+ elif signal == "deviceChanged":
+ print "TODO:Listen comar signal deviceChanged "
+ elif signal == "connectionChanged":
+ if args[0] == u"changed":
+ pass#Nothing to do ?
+ elif args[0] == u"added":
+ self._holder.add_profile(package,
+ args[1],
+ self.get_state(package,
+ args[1]))
+ elif args[0] == u"deleted":
+ self._holder.remove_profile(package,
+ args[1])
+ def _get_profiles(self):
+ """get profiles from iface
+ """
+ for package in self.iface.packages():
+ for connection in self.iface.connections(package):
+ state = self.get_state(package, connection)
+ self._holder.add_profile(package,
+ connection,
+ state)
|
rdno/pardus-network-manager-gtk
|
e71fbf9fea0cc8f739baacb080164af6370f737e
|
added base New Wifi Connection Window
|
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index 6e30d01..ab98ac7 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,609 +1,737 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
"""A special widget contains connection related stuff
"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
self._createUI()
def _createUI(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.setMode(self._state.split(' '))
def setMode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- `args`: state, detail
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
self._info.set_markup('<span color="green">'+
args[1]+
'</span>')
def connectSignals(self, click_signal, edit_signal, delete_signal):
"""connect widgets signals
Arguments:
- `click_signal`: toggle connection signal
- `edit_signal`: edit signal
- `delete_signal`: delete signal
"""
self.check_btn.connect("pressed", click_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.edit_btn.connect("clicked", edit_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.delete_btn.connect("clicked", delete_signal,
{"package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
class WifiItemHolder(gtk.ScrolledWindow):
"""holder for wifi connections
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
return data
return None
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
+class NewWifiConnectionItem(gtk.Table):
+ """new wifi connection
+ """
+ def __init__(self,
+ device_id,
+ connection):
+ """init
+ Arguments:
+ - `device_id`: connection device
+ - `connection`: scanRemote callback dict
+ example: {'remote':'ESSID Name',
+ 'quality':'60',
+ 'quality_max':'100'
+ 'encryption':'wpa-psk',
+ ...}
+ """
+ gtk.Table.__init__(self, rows=2, columns=4)
+ self._device_id = device_id
+ self._connection = connection;
+ self._create_ui();
+ def _create_ui(self):
+ """creates UI
+ """
+ frac = float(self._connection['quality'])/ \
+ float(self._connection['quality_max'])
+ per = self._connection['quality']
+ self._quality_bar = gtk.ProgressBar()
+ self._quality_bar.set_fraction(frac)
+ self._quality_bar.set_text(_("%d%%") % int(per))
+
+ self._name_txt = gtk.Label(self._connection['remote'])
+ self._name_txt.set_alignment(0.0 , 0.5)
+
+ self._encrypt_txt = gtk.Label(self._connection['encryption'])
+ self._encrypt_txt.set_alignment(0.0 , 0.5)
+
+ self._connect_btn = gtk.Button(_("Connect"))
+
+ self.attach(self._quality_bar, 0, 1, 0, 2,
+ gtk.SHRINK, gtk.SHRINK)
+ self.attach(self._name_txt, 1, 2, 0, 1,
+ gtk.EXPAND|gtk.FILL, gtk.SHRINK)
+ self.attach(self._encrypt_txt, 1, 2, 1, 2,
+ gtk.SHRINK, gtk.SHRINK)
+ self.attach(self._connect_btn, 2, 3, 0, 2,
+ gtk.SHRINK, gtk.SHRINK)
+
+gobject.type_register(NewWifiConnectionItem)
+
+class NewConnectionWindow(gtk.Window):
+ """show new connections as a list
+ """
+
+ def __init__(self, iface):
+ """init
+ Arguments:
+ - `iface`: NetworkIface
+ """
+ gtk.Window.__init__(self)
+ self._iface = iface
+ self.set_title(_("New Connection"))
+ self._package = "wireless_tools"
+ self._devices = self._iface.devices(self._package).keys()
+ self._create_ui();
+ self._cons = [] #connections
+ self.scan()
+ def _create_ui(self):
+ """creates ui
+ """
+ self._ui = gtk.VBox()
+ self.add(self._ui)
+
+ self._refresh_btn = gtk.Button("")
+ self._refresh_btn.connect("clicked", self.scan)
+ self._ui.add(self._refresh_btn)
+
+ self._list= gtk.VBox()
+ self._ui.add(self._list)
+ def _set_scanning(self, status):
+ """disable/enable refresh btn
+ Arguments:
+ - `status`: if True then disable button
+ """
+ if status:
+ self._refresh_btn.set_label(_("Refreshing..."))
+ else:
+ self._refresh_btn.set_label(_("Refresh"))
+ self._refresh_btn.set_sensitive(not status)
+ def scan(self, widget=None):
+ """scan for wifi networks
+ """
+ self._set_scanning(True)
+ d = self._devices[0] #TODO:more than one device support
+ self._iface.scanRemote(d, self._package,
+ self._scan_callback)
+ def _scan_callback(self, package, exception, args):
+ """wifi scan callback
+
+ Arguments:
+ - `package`: package name
+ - `exception`: exception
+ - `args`: connection array
+ """
+ self._set_scanning(False)
+ if not exception:
+ self._show_list(args[0])
+ else:
+ print exception
+ def _show_list(self, connections):
+ """show list
+
+ Arguments:
+ - `connections`: connections array
+ """
+ d = self._devices[0]
+ #remove old ones
+ map(self._list.remove, self._cons)
+ self._cons = [NewWifiConnectionItem(d, x)
+ for x in connections]
+ #add new ones
+ map(self._list.add, self._cons)
+ self.show_all()
+
+gobject.type_register(NewConnectionWindow)
+
class dummy_data_creator(object):
"""create
"""
def __init__(self,
device,
device_name,
essid=None):
"""init
Arguments:
- `device`:
- `essid`:
"""
self._wireless = False
self._device = device
self._device_name = device_name
if essid is not None:
self._essid = essid
self._wireless = True
def get(self):
"""get data
"""
data = {}
if self._wireless:
data["name"] = self._essid
else:
data["name"] = "Kablo" #TODO: what?
data["device_id"] = self._device
data["device_name"] = self._device_name
#Network Settings
data["net_mode"] = "auto"
data["net_address"] = ""
data["net_mask"] = ""
data["net_gateway"] = ""
#Name Server Settings
data["name_mode"] = "default"
data["name_server"] = ""
return data
class MainInterface(object):
"""Imports main window glade
"""
def __init__(self):
"""import glade
"""
bind_glade_domain()
self._xml = glade.XML("ui/main.glade")
self._xml.signal_connect("on_window_main_destroy",
gtk.main_quit)
self._xml.signal_connect("on_new_clicked",
- self.brand_new)
+ self.show_news)
self._window = self._xml.get_widget("window_main")
self._holder = self._xml.get_widget("holder")
self.iface = NetworkIface()
+ def show_news(self, widget):
+ a = NewConnectionWindow(self.iface)
+ a.show()
def brand_new(self, widget):
"""deneme
Arguments:
- `widget`:
"""
pack = "net_tools"
device = self.iface.devices(pack).keys()[0]
name = self.iface.devices(pack)[device]
a = EditInterface(pack,
"",
is_new=True,
new_data=dummy_data_creator(device, name).get())
a.getWindow().show()
def getWindow(self):
"""returns window
"""
return self._window
def getHolder(self):
"""returns holder
"""
return self._holder
# --- Edit Window Sections (in ui: frame)
class EditSection(object):
def __init__(self, parent):
super(EditSection, self).__init__()
self.get = parent.get
self.signal_connect = parent._xml.signal_connect
self.parent = parent
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
def get_text_of(self, name):
"""gets text from widget in unicode"""
return unicode(self.get(name).get_text())
def collect_data(self, data):
"""collect data from ui and append datas to
given(data) dictionary"""
pass
class ProfileSection(EditSection):
def __init__(self, parent):
super(ProfileSection, self).__init__(parent)
def insert_data_and_show(self, data):
self.if_available_set(data, "name",
self.get("profilename").set_text)
self.if_available_set(data, "device_name",
self.get("device_name_label").set_text)
self.device_id = data["device_id"]
#TODO:more than one device support
def collect_data(self, data):
super(ProfileSection, self).collect_data(data)
data["name"] = self.get_text_of("profilename")
data["device_id"] = unicode(self.device_id)
class NetworkSettingsSection(EditSection):
def __init__(self, parent):
super(NetworkSettingsSection, self).__init__(parent)
def _on_type_changed(self, widget):
if widget is self.get("dhcp_rb"):
self.set_manual_network(False)
else:
self.set_manual_network(True)
def set_manual_network(self, state):
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
# custom things
self.get("custom_gateway").set_sensitive(not state)
self.get("custom_address").set_sensitive(not state)
if not state:
self._on_custom_address(self.get("custom_address"))
self._on_custom_gateway(self.get("custom_gateway"))
def _on_custom_address(self, widget):
state = widget.get_active()
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
def _on_custom_gateway(self, widget):
state = widget.get_active()
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
def listen_signals(self):
self.signal_connect("on_dhcp_rb_clicked",
self._on_type_changed)
self.signal_connect("on_manual_rb_clicked",
self._on_type_changed)
self.signal_connect("on_custom_gateway_toggled",
self._on_custom_gateway)
self.signal_connect("on_custom_address_toggled",
self._on_custom_address)
def insert_data_and_show(self, data):
if data.has_key("net_mode"):
self.listen_signals()
if data["net_mode"] == "auto":
self.get("dhcp_rb").set_active(True)
self.set_manual_network(False)
if self.is_custom(data, "net_gateway"):
self.get("custom_gateway").set_active(True)
if self.is_custom(data, "net_address"):
self.get("custom_address").set_active(True)
else:
self.get("manual_rb").set_active(False)
self.set_manual_network(True)
self.if_available_set(data, "net_address",
self.get("address").set_text)
self.if_available_set(data, "net_mask",
self.get("networkmask").set_text)
self.if_available_set(data, "net_gateway",
self.get("gateway").set_text)
def is_custom(self, data, key):
if data.has_key(key):
if data[key] != "":
return True
return False
def collect_data(self, data):
super(NetworkSettingsSection, self).collect_data(data)
data["net_mode"] = u"auto"
data["net_address"] = u""
data["net_mask"] = u""
data["net_gateway"] = u""
if self.get("manual_rb").get_active():
data["net_mode"] = u"manual"
if self.get("address").state == gtk.STATE_NORMAL:
data["net_address"] = self.get_text_of("address")
data["net_mask"] = self.get_text_of("networkmask")
if self.get("gateway").state == gtk.STATE_NORMAL:
data["net_gateway"] = self.get_text_of("gateway")
class NameServerSection(EditSection):
def __init__(self, parent):
super(NameServerSection, self).__init__(parent)
def set_custom_name(self, state):
self.get("ns_custom_text").set_sensitive(state)
def _on_type_changed(self, widget):
if widget is self.get("ns_custom_rb"):
self.set_custom_name(True)
else:
self.set_custom_name(False)
def listen_signals(self):
self.signal_connect("on_ns_default_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_custom_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_auto_rb_clicked",
self._on_type_changed)
def insert_data_and_show(self, data):
self.listen_signals()
if data.has_key("name_mode"):
if data["name_mode"] == "default":
self.get("ns_default_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "auto":
self.get("ns_auto_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "custom":
self.get("ns_custom_rb").set_active(True)
self.set_custom_name(True)
self.if_available_set(data, "name_server",
self.get("ns_custom_text").set_text)
def collect_data(self, data):
super(NameServerSection, self).collect_data(data)
data["name_mode"] = u"default"
data["name_server"] = u""
if self.get("ns_auto_rb").get_active():
data["name_mode"] = u"auto"
if self.get("ns_custom_rb").get_active():
data["name_mode"] = u"custom"
data["name_server"] = self.get_text_of("ns_custom_text")
class WirelessSection(EditSection):
def __init__(self, parent):
super(WirelessSection, self).__init__(parent)
self.iface = parent.iface
self.package = parent._package
self.connection = parent._connection
self.is_new = parent.is_new
# --- Password related
def show_password(self, state):
if not state:
self.get("hidepass_cb").hide()
self.get("pass_text").hide()
self.get("pass_lb").hide()
else:
self.get("hidepass_cb").show()
self.get("pass_text").show()
self.get("pass_lb").show()
def hide_password(self, widget):
visibility = not widget.get_active()
self.get("pass_text").set_visibility(visibility)
# end Password related
def scan(self, widget=None):
self.get("scan_btn").hide()
self.wifiitems.set_scanning(True)
self.iface.scanRemote(self.device , self.package, self.wifilist)
def security_types_changed(self, widget):
index = widget.get_active()
if index == 0:
self.show_password(False)
else:
self.show_password(True)
def listen_signals(self):
self.signal_connect("on_security_types_changed",
self.security_types_changed)
self.signal_connect("on_hidepass_cb_toggled",
self.hide_password)
def set_security_types_style(self):
##Security Type ComboBox
model = gtk.ListStore(str)
security_types = self.get("security_types")
security_types.set_model(model)
cell = gtk.CellRendererText()
security_types.pack_start(cell)
security_types.add_attribute(cell,'text',0)
def prepare_security_types(self, authType):
self.set_security_types_style()
noauth = _("No Authentication")
self._authMethods = [("none", noauth)]
append_to_types = self.get("security_types").append_text
append_to_types(noauth)
self.get("security_types").set_active(0)
index = 1
self.with_password = False
for name, desc in self.iface.authMethods(self.package):
append_to_types(desc)
self._authMethods.append((name, desc))
if name == authType:
self.get("security_types").set_active(index)
self.with_password = True
index += 1
def on_wifi_clicked(self, widget, callback_data):
data = callback_data["get_connection"]()
self.get("essid_text").set_text(data["remote"])
for index, method in enumerate(self._authMethods):
if method[0] == data["encryption"]:
self.get("security_types").set_active(index)
def wifilist(self, package, exception, args):
self.get("scan_btn").show()
self.signal_connect("on_scan_btn_clicked",
self.scan)
if not exception:
self.wifiitems.getConnections(args[0])
self.wifiitems.listen_change(self.on_wifi_clicked)
else:
print exception
def insert_data_and_show(self, data, caps):
self.listen_signals()
self.device = data["device_id"]
self.if_available_set(data, "remote",
self.get("essid_text").set_text)
modes = caps["modes"].split(",")
if ("auth" in modes) and (not self.is_new):
authType = self.iface.authType(self.package,
self.connection)
self.prepare_security_types(authType)
self.get("hidepass_cb").set_active(True)
if self.with_password:
authType = self.iface.authType(self.package,
self.connection)
authInfo = self.iface.authInfo(self.package,
self.connection)
authParams = self.iface.authParameters(self.package,
authType)
if len(authParams) == 1:
password = authInfo.values()[0]
self.get("pass_text").set_text(password)
elif len(authParams) > 1:
print "\nTODO:Dynamic WEP support"
self.show_password(self.with_password)
if self.is_new:
pass
self.wifiitems = WifiItemHolder()
self.get("wireless_table").attach(self.wifiitems,
0, 1, 0, 3,
gtk.EXPAND|gtk.FILL,
gtk.EXPAND|gtk.FILL)
self.scan()
def collect_data(self, data):
super(WirelessSection, self).collect_data(data)
data["remote"] = self.get_text_of("essid_text")
data["apmac"] = u"" #i think it is Access Point MAC
#Security
data["auth"] = unicode(self._authMethods[
self.get("security_types").get_active()][0])
if data["auth"] != u"none":
params = self.iface.authParameters("wireless_tools",
data["auth"])
if len(params) == 1:
key = "auth_%s" % params[0][0]
data[key] = self.get_text_of("pass_text")
else:
print "TODO:Dynamic WEP Support"
# end Edit Window Sections
class EditInterface(object):
"""Imports edit window glade
"""
def __init__(self,
package,
connection="",
is_new=False,
new_data={}):
"""init
Arguments:
- `package`:
- `connection`:
"""
bind_glade_domain()
self.iface = NetworkIface()
self._package = package
self._connection = connection
self._xml = glade.XML("ui/edit.glade")
self.get = self._xml.get_widget
self.listen_signals()
self.is_new = is_new
self.new_data = new_data
self.insertData()
def apply(self, widget):
data = self.collect_data()
try:
self.iface.updateConnection(self._package,
data["name"],
data)
except Exception, e:
print "Exception:", unicode(e)
if not self.name == data["name"]:
self.iface.deleteConnection(self._package, self.name)
if self.is_up:
self.iface.connect(self._package, self.name)
self.getWindow().destroy()
def cancel(self, widget):
self.getWindow().destroy()
def listen_signals(self):
self._xml.signal_connect("apply_btn_clicked",
self.apply)
self._xml.signal_connect("cancel_btn_clicked",
self.cancel)
def insertData(self):
"""show preferences
"""
if not self.is_new:
data = self.iface.info(self._package,
self._connection)
else:
data = self.new_data
self.name = data["name"]
self.is_up = False
if data.has_key("state"):
if data["state"][0:2] == "up":
self.is_up = True
#Profile Frame
self.profile_frame = ProfileSection(self)
self.profile_frame.insert_data_and_show(data)
#Network Settings Frame
self.network_frame = NetworkSettingsSection(self)
self.network_frame.insert_data_and_show(data)
#Name Servers Frame
self.name_frame = NameServerSection(self)
self.name_frame.insert_data_and_show(data)
# Wireless Frame
if self._package == "wireless_tools":
caps = self.iface.capabilities(self._package)
self.wireless_frame = WirelessSection(self)
self.wireless_frame.insert_data_and_show(data, caps)
else:
self.get("wireless_frame").hide()
def collect_data(self):
data = {}
self.profile_frame.collect_data(data)
self.network_frame.collect_data(data)
self.name_frame.collect_data(data)
if self._package == "wireless_tools":
self.wireless_frame.collect_data(data)
return data
def getWindow(self):
"""returns window
"""
return self.get("window_edit")
diff --git a/ui/main.glade b/ui/main.glade
index ff32efb..94d4120 100644
--- a/ui/main.glade
+++ b/ui/main.glade
@@ -1,46 +1,59 @@
<?xml version="1.0"?>
<glade-interface>
<!-- interface-requires gtk+ 2.16 -->
<!-- interface-naming-policy project-wide -->
<widget class="GtkWindow" id="window_main">
<property name="title" translatable="yes" comments="Main Window Title">Network Manager</property>
<property name="window_position">center</property>
<property name="default_width">300</property>
<signal name="destroy" handler="on_window_main_destroy"/>
<child>
<widget class="GtkVBox" id="vbox1">
<property name="visible">True</property>
<property name="orientation">vertical</property>
<child>
- <widget class="GtkButton" id="new">
- <property name="label" translatable="yes">new connection</property>
+ <widget class="GtkHBox" id="hbox1">
<property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">True</property>
- <signal name="clicked" handler="on_new_clicked"/>
+ <child>
+ <widget class="GtkButton" id="new">
+ <property name="label" translatable="yes">New Connection</property>
+ <property name="visible">True</property>
+ <property name="can_focus">True</property>
+ <property name="receives_default">True</property>
+ <signal name="clicked" handler="on_new_clicked"/>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="fill">False</property>
+ <property name="position">0</property>
+ </packing>
+ </child>
+ <child>
+ <placeholder/>
+ </child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkScrolledWindow" id="holder">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="hscrollbar_policy">automatic</property>
<property name="vscrollbar_policy">automatic</property>
<property name="shadow_type">in</property>
<child>
<placeholder/>
</child>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
</widget>
</child>
</widget>
</glade-interface>
|
rdno/pardus-network-manager-gtk
|
7344e074a68f3ed5404018e97cb79f7e0a2c38ae
|
added .gitignore from old repo
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..6ee580a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
+*~
+*.pyc
+TAGS
+.directory
+#*
+*.glade.h
|
rdno/pardus-network-manager-gtk
|
501ccffb9ffa36df12ac26e51cce3ccc055f2357
|
new connection via dummy_data_creator
|
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index b91c134..6e30d01 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,539 +1,609 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
"""A special widget contains connection related stuff
"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
self._createUI()
def _createUI(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.setMode(self._state.split(' '))
def setMode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- `args`: state, detail
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
self._info.set_markup('<span color="green">'+
args[1]+
'</span>')
def connectSignals(self, click_signal, edit_signal, delete_signal):
"""connect widgets signals
Arguments:
- `click_signal`: toggle connection signal
- `edit_signal`: edit signal
- `delete_signal`: delete signal
"""
self.check_btn.connect("pressed", click_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.edit_btn.connect("clicked", edit_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.delete_btn.connect("clicked", delete_signal,
{"package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
class WifiItemHolder(gtk.ScrolledWindow):
"""holder for wifi connections
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
return data
return None
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
+class dummy_data_creator(object):
+ """create
+ """
+ def __init__(self,
+ device,
+ device_name,
+ essid=None):
+ """init
+ Arguments:
+ - `device`:
+ - `essid`:
+ """
+ self._wireless = False
+ self._device = device
+ self._device_name = device_name
+ if essid is not None:
+ self._essid = essid
+ self._wireless = True
+ def get(self):
+ """get data
+ """
+ data = {}
+ if self._wireless:
+ data["name"] = self._essid
+ else:
+ data["name"] = "Kablo" #TODO: what?
+ data["device_id"] = self._device
+ data["device_name"] = self._device_name
+ #Network Settings
+ data["net_mode"] = "auto"
+ data["net_address"] = ""
+ data["net_mask"] = ""
+ data["net_gateway"] = ""
+ #Name Server Settings
+ data["name_mode"] = "default"
+ data["name_server"] = ""
+ return data
class MainInterface(object):
"""Imports main window glade
"""
def __init__(self):
"""import glade
"""
bind_glade_domain()
self._xml = glade.XML("ui/main.glade")
self._xml.signal_connect("on_window_main_destroy",
gtk.main_quit)
+ self._xml.signal_connect("on_new_clicked",
+ self.brand_new)
self._window = self._xml.get_widget("window_main")
self._holder = self._xml.get_widget("holder")
+ self.iface = NetworkIface()
+ def brand_new(self, widget):
+ """deneme
+
+ Arguments:
+
+ - `widget`:
+ """
+ pack = "net_tools"
+ device = self.iface.devices(pack).keys()[0]
+ name = self.iface.devices(pack)[device]
+ a = EditInterface(pack,
+ "",
+ is_new=True,
+ new_data=dummy_data_creator(device, name).get())
+ a.getWindow().show()
+
def getWindow(self):
"""returns window
"""
return self._window
def getHolder(self):
"""returns holder
"""
return self._holder
# --- Edit Window Sections (in ui: frame)
class EditSection(object):
def __init__(self, parent):
super(EditSection, self).__init__()
self.get = parent.get
self.signal_connect = parent._xml.signal_connect
self.parent = parent
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
def get_text_of(self, name):
"""gets text from widget in unicode"""
return unicode(self.get(name).get_text())
def collect_data(self, data):
"""collect data from ui and append datas to
given(data) dictionary"""
pass
class ProfileSection(EditSection):
def __init__(self, parent):
super(ProfileSection, self).__init__(parent)
- def show_ui(self, data):
- self.get("profilename").set_text(data[u"name"])
+ def insert_data_and_show(self, data):
+ self.if_available_set(data, "name",
+ self.get("profilename").set_text)
self.if_available_set(data, "device_name",
self.get("device_name_label").set_text)
self.device_id = data["device_id"]
#TODO:more than one device support
def collect_data(self, data):
super(ProfileSection, self).collect_data(data)
data["name"] = self.get_text_of("profilename")
data["device_id"] = unicode(self.device_id)
class NetworkSettingsSection(EditSection):
def __init__(self, parent):
super(NetworkSettingsSection, self).__init__(parent)
def _on_type_changed(self, widget):
if widget is self.get("dhcp_rb"):
self.set_manual_network(False)
else:
self.set_manual_network(True)
def set_manual_network(self, state):
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
# custom things
self.get("custom_gateway").set_sensitive(not state)
self.get("custom_address").set_sensitive(not state)
if not state:
self._on_custom_address(self.get("custom_address"))
self._on_custom_gateway(self.get("custom_gateway"))
def _on_custom_address(self, widget):
state = widget.get_active()
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
def _on_custom_gateway(self, widget):
state = widget.get_active()
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
def listen_signals(self):
self.signal_connect("on_dhcp_rb_clicked",
self._on_type_changed)
self.signal_connect("on_manual_rb_clicked",
self._on_type_changed)
self.signal_connect("on_custom_gateway_toggled",
self._on_custom_gateway)
self.signal_connect("on_custom_address_toggled",
self._on_custom_address)
- def show_ui(self, data):
+ def insert_data_and_show(self, data):
if data.has_key("net_mode"):
self.listen_signals()
if data["net_mode"] == "auto":
self.get("dhcp_rb").set_active(True)
self.set_manual_network(False)
if self.is_custom(data, "net_gateway"):
self.get("custom_gateway").set_active(True)
if self.is_custom(data, "net_address"):
self.get("custom_address").set_active(True)
else:
self.get("manual_rb").set_active(False)
self.set_manual_network(True)
self.if_available_set(data, "net_address",
self.get("address").set_text)
self.if_available_set(data, "net_mask",
self.get("networkmask").set_text)
self.if_available_set(data, "net_gateway",
self.get("gateway").set_text)
def is_custom(self, data, key):
if data.has_key(key):
if data[key] != "":
return True
return False
def collect_data(self, data):
super(NetworkSettingsSection, self).collect_data(data)
data["net_mode"] = u"auto"
data["net_address"] = u""
data["net_mask"] = u""
data["net_gateway"] = u""
if self.get("manual_rb").get_active():
data["net_mode"] = u"manual"
if self.get("address").state == gtk.STATE_NORMAL:
data["net_address"] = self.get_text_of("address")
data["net_mask"] = self.get_text_of("networkmask")
if self.get("gateway").state == gtk.STATE_NORMAL:
data["net_gateway"] = self.get_text_of("gateway")
class NameServerSection(EditSection):
def __init__(self, parent):
super(NameServerSection, self).__init__(parent)
def set_custom_name(self, state):
self.get("ns_custom_text").set_sensitive(state)
def _on_type_changed(self, widget):
if widget is self.get("ns_custom_rb"):
self.set_custom_name(True)
else:
self.set_custom_name(False)
def listen_signals(self):
self.signal_connect("on_ns_default_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_custom_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_auto_rb_clicked",
self._on_type_changed)
- def show_ui(self, data):
+ def insert_data_and_show(self, data):
+ self.listen_signals()
if data.has_key("name_mode"):
- self.listen_signals()
if data["name_mode"] == "default":
self.get("ns_default_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "auto":
self.get("ns_auto_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "custom":
self.get("ns_custom_rb").set_active(True)
self.set_custom_name(True)
self.if_available_set(data, "name_server",
self.get("ns_custom_text").set_text)
def collect_data(self, data):
super(NameServerSection, self).collect_data(data)
data["name_mode"] = u"default"
data["name_server"] = u""
if self.get("ns_auto_rb").get_active():
data["name_mode"] = u"auto"
if self.get("ns_custom_rb").get_active():
data["name_mode"] = u"custom"
data["name_server"] = self.get_text_of("ns_custom_text")
class WirelessSection(EditSection):
def __init__(self, parent):
super(WirelessSection, self).__init__(parent)
self.iface = parent.iface
self.package = parent._package
self.connection = parent._connection
+ self.is_new = parent.is_new
# --- Password related
def show_password(self, state):
if not state:
self.get("hidepass_cb").hide()
self.get("pass_text").hide()
self.get("pass_lb").hide()
else:
self.get("hidepass_cb").show()
self.get("pass_text").show()
self.get("pass_lb").show()
def hide_password(self, widget):
visibility = not widget.get_active()
self.get("pass_text").set_visibility(visibility)
# end Password related
def scan(self, widget=None):
self.get("scan_btn").hide()
self.wifiitems.set_scanning(True)
self.iface.scanRemote(self.device , self.package, self.wifilist)
def security_types_changed(self, widget):
index = widget.get_active()
if index == 0:
self.show_password(False)
else:
self.show_password(True)
def listen_signals(self):
self.signal_connect("on_security_types_changed",
self.security_types_changed)
self.signal_connect("on_hidepass_cb_toggled",
self.hide_password)
def set_security_types_style(self):
##Security Type ComboBox
model = gtk.ListStore(str)
security_types = self.get("security_types")
security_types.set_model(model)
cell = gtk.CellRendererText()
security_types.pack_start(cell)
security_types.add_attribute(cell,'text',0)
def prepare_security_types(self, authType):
self.set_security_types_style()
noauth = _("No Authentication")
self._authMethods = [("none", noauth)]
append_to_types = self.get("security_types").append_text
append_to_types(noauth)
self.get("security_types").set_active(0)
index = 1
self.with_password = False
for name, desc in self.iface.authMethods(self.package):
append_to_types(desc)
self._authMethods.append((name, desc))
if name == authType:
self.get("security_types").set_active(index)
self.with_password = True
index += 1
def on_wifi_clicked(self, widget, callback_data):
data = callback_data["get_connection"]()
self.get("essid_text").set_text(data["remote"])
for index, method in enumerate(self._authMethods):
if method[0] == data["encryption"]:
self.get("security_types").set_active(index)
def wifilist(self, package, exception, args):
self.get("scan_btn").show()
self.signal_connect("on_scan_btn_clicked",
self.scan)
if not exception:
self.wifiitems.getConnections(args[0])
self.wifiitems.listen_change(self.on_wifi_clicked)
else:
print exception
- def show_ui(self, data, caps):
+ def insert_data_and_show(self, data, caps):
self.listen_signals()
self.device = data["device_id"]
self.if_available_set(data, "remote",
self.get("essid_text").set_text)
modes = caps["modes"].split(",")
- if "auth" in modes:
+ if ("auth" in modes) and (not self.is_new):
authType = self.iface.authType(self.package,
self.connection)
self.prepare_security_types(authType)
self.get("hidepass_cb").set_active(True)
if self.with_password:
authType = self.iface.authType(self.package,
self.connection)
authInfo = self.iface.authInfo(self.package,
self.connection)
authParams = self.iface.authParameters(self.package,
authType)
if len(authParams) == 1:
password = authInfo.values()[0]
self.get("pass_text").set_text(password)
elif len(authParams) > 1:
print "\nTODO:Dynamic WEP support"
self.show_password(self.with_password)
- self.wifiitems = WifiItemHolder()
- self.get("wireless_table").attach(self.wifiitems,
- 0, 1, 0, 3,
- gtk.EXPAND|gtk.FILL,
- gtk.EXPAND|gtk.FILL)
+ if self.is_new:
+ pass
+ self.wifiitems = WifiItemHolder()
+ self.get("wireless_table").attach(self.wifiitems,
+ 0, 1, 0, 3,
+ gtk.EXPAND|gtk.FILL,
+ gtk.EXPAND|gtk.FILL)
self.scan()
def collect_data(self, data):
super(WirelessSection, self).collect_data(data)
data["remote"] = self.get_text_of("essid_text")
- data["apmac"] = u"" #??? what is it
+ data["apmac"] = u"" #i think it is Access Point MAC
#Security
data["auth"] = unicode(self._authMethods[
self.get("security_types").get_active()][0])
if data["auth"] != u"none":
params = self.iface.authParameters("wireless_tools",
data["auth"])
if len(params) == 1:
key = "auth_%s" % params[0][0]
data[key] = self.get_text_of("pass_text")
else:
print "TODO:Dynamic WEP Support"
# end Edit Window Sections
class EditInterface(object):
"""Imports edit window glade
"""
- def __init__(self, package, connection):
+ def __init__(self,
+ package,
+ connection="",
+ is_new=False,
+ new_data={}):
"""init
Arguments:
- `package`:
- `connection`:
"""
bind_glade_domain()
self.iface = NetworkIface()
self._package = package
self._connection = connection
self._xml = glade.XML("ui/edit.glade")
self.get = self._xml.get_widget
self.listen_signals()
+ self.is_new = is_new
+ self.new_data = new_data
self.insertData()
def apply(self, widget):
data = self.collect_data()
try:
self.iface.updateConnection(self._package,
data["name"],
data)
except Exception, e:
print "Exception:", unicode(e)
if not self.name == data["name"]:
self.iface.deleteConnection(self._package, self.name)
if self.is_up:
self.iface.connect(self._package, self.name)
self.getWindow().destroy()
def cancel(self, widget):
self.getWindow().destroy()
def listen_signals(self):
self._xml.signal_connect("apply_btn_clicked",
self.apply)
self._xml.signal_connect("cancel_btn_clicked",
self.cancel)
def insertData(self):
"""show preferences
"""
- data = self.iface.info(self._package,
- self._connection)
+ if not self.is_new:
+ data = self.iface.info(self._package,
+ self._connection)
+ else:
+ data = self.new_data
self.name = data["name"]
self.is_up = False
if data.has_key("state"):
if data["state"][0:2] == "up":
self.is_up = True
#Profile Frame
self.profile_frame = ProfileSection(self)
- self.profile_frame.show_ui(data)
+ self.profile_frame.insert_data_and_show(data)
#Network Settings Frame
self.network_frame = NetworkSettingsSection(self)
- self.network_frame.show_ui(data)
+ self.network_frame.insert_data_and_show(data)
#Name Servers Frame
self.name_frame = NameServerSection(self)
- self.name_frame.show_ui(data)
+ self.name_frame.insert_data_and_show(data)
# Wireless Frame
if self._package == "wireless_tools":
caps = self.iface.capabilities(self._package)
self.wireless_frame = WirelessSection(self)
- self.wireless_frame.show_ui(data, caps)
+ self.wireless_frame.insert_data_and_show(data, caps)
else:
self.get("wireless_frame").hide()
+
def collect_data(self):
data = {}
self.profile_frame.collect_data(data)
self.network_frame.collect_data(data)
self.name_frame.collect_data(data)
if self._package == "wireless_tools":
self.wireless_frame.collect_data(data)
return data
def getWindow(self):
"""returns window
"""
return self.get("window_edit")
diff --git a/ui/main.glade b/ui/main.glade
index f092dd8..ff32efb 100644
--- a/ui/main.glade
+++ b/ui/main.glade
@@ -1,23 +1,46 @@
<?xml version="1.0"?>
<glade-interface>
<!-- interface-requires gtk+ 2.16 -->
<!-- interface-naming-policy project-wide -->
<widget class="GtkWindow" id="window_main">
<property name="title" translatable="yes" comments="Main Window Title">Network Manager</property>
<property name="window_position">center</property>
<property name="default_width">300</property>
<signal name="destroy" handler="on_window_main_destroy"/>
<child>
- <widget class="GtkScrolledWindow" id="holder">
+ <widget class="GtkVBox" id="vbox1">
<property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="hscrollbar_policy">automatic</property>
- <property name="vscrollbar_policy">automatic</property>
- <property name="shadow_type">in</property>
+ <property name="orientation">vertical</property>
<child>
- <placeholder/>
+ <widget class="GtkButton" id="new">
+ <property name="label" translatable="yes">new connection</property>
+ <property name="visible">True</property>
+ <property name="can_focus">True</property>
+ <property name="receives_default">True</property>
+ <signal name="clicked" handler="on_new_clicked"/>
+ </widget>
+ <packing>
+ <property name="expand">False</property>
+ <property name="fill">False</property>
+ <property name="position">0</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkScrolledWindow" id="holder">
+ <property name="visible">True</property>
+ <property name="can_focus">True</property>
+ <property name="hscrollbar_policy">automatic</property>
+ <property name="vscrollbar_policy">automatic</property>
+ <property name="shadow_type">in</property>
+ <child>
+ <placeholder/>
+ </child>
+ </widget>
+ <packing>
+ <property name="position">1</property>
+ </packing>
</child>
</widget>
</child>
</widget>
</glade-interface>
|
rdno/pardus-network-manager-gtk
|
73bd82eacc7cc0edfbad320af31eff7fdc4b29b7
|
support for deleting connections
|
diff --git a/network-manager-gtk.py b/network-manager-gtk.py
index fd41d18..dccddb0 100755
--- a/network-manager-gtk.py
+++ b/network-manager-gtk.py
@@ -1,114 +1,131 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import os
import pygtk
pygtk.require('2.0')
import gtk
import gobject
from network_manager_gtk.backend import NetworkIface
from network_manager_gtk.widgets import ConnectionWidget
from network_manager_gtk.widgets import MainInterface
from network_manager_gtk.widgets import EditInterface
+from network_manager_gtk.translation import _
class Base(object):
def __init__(self):
self._dbusMainLoop()
self.iface = NetworkIface()
#ui
self.main = MainInterface()
self.window = self.main.getWindow()
# show connection as Widgets
self.widgets = {}
self.showConnections()
self.holder = self.main.getHolder()
self.holder.add_with_viewport(self.vbox)
# listen for changes
self.iface.listen(self._listener)
def _onConnectionClicked(self, widget, callback_data):
self.iface.toggle(callback_data['package'],
callback_data['connection'])
def _onConnectionEdit(self, widget, callback_data):
- a = EditInterface(callback_data['package'],
- callback_data['connection'])
- a.getWindow().show()
+ try:
+ a = EditInterface(callback_data['package'],
+ callback_data['connection'])
+ a.getWindow().props.modal = True
+ a.getWindow().show()
+ except Exception, e:
+ print "Exception:", e
def _onConnectionDelete(self, widget, callback_data):
- print "TODO:onConnection Delete"
+ message = _("Do you wanna delete the connection '%s' ? " % \
+ callback_data["connection"])
+ dialog = gtk.MessageDialog(type=gtk.MESSAGE_WARNING,
+ buttons=gtk.BUTTONS_YES_NO,
+ message_format=message)
+ response = dialog.run()
+ if response == gtk.RESPONSE_YES:
+ try:
+ self.iface.deleteConnection(callback_data['package'],
+ callback_data['connection'])
+ except Exception, e:
+ print "Exception:",e
+ dialog.destroy()
def showConnections(self):
"""show connection on gui
"""
self.vbox = gtk.VBox(homogeneous=False, spacing=10)
for package in self.iface.packages():
self.widgets[package] = {}
for connection in self.iface.connections(package):
self.add_to_vbox(package, connection)
def add_to_vbox(self, package, connection):
state = self.iface.info(package, connection)[u"state"]
con_wg = ConnectionWidget(package,
connection,
state)
con_wg.connectSignals(self._onConnectionClicked,
self._onConnectionEdit,
self._onConnectionDelete)
self.vbox.pack_start(con_wg, expand=False, fill=False)
self.widgets[package][connection] = con_wg
def _listener(self, package, signal, args):
"""comar listener
Arguments:
- `package`: package of item
- `signal`: comar signal type
- `args`: arguments
"""
args = map(lambda x: unicode(x), list(args))
if signal == "stateChanged":
self.widgets[package][args[0]].setMode(args[1:])
elif signal == "deviceChanged":
print "TODO:Listen comar signal deviceChanged "
elif signal == "connectionChanged":
if args[0] == u"changed":
pass#Nothing to do ?
elif args[0] == u"added":
self.add_to_vbox(package, args[1])
self.vbox.show_all()
elif args[0] == u"deleted":
self.vbox.remove(self.widgets[package][args[1]])
pass
def _dbusMainLoop(self):
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default = True)
def run(self, argv=None):
"""Runs the program
Arguments:
- `argv`: sys.argv
"""
self.window.show_all()
gtk.main()
if __name__ == "__main__":
import sys
app = Base()
app.run(sys.argv)
|
rdno/pardus-network-manager-gtk
|
26e4a9c2b1ef752b7030c57821443c4b44947e4b
|
fixed some stupid things
|
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index 63772a3..b91c134 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,542 +1,539 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
"""A special widget contains connection related stuff
"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
self._createUI()
def _createUI(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.setMode(self._state.split(' '))
def setMode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- `args`: state, detail
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
self._info.set_markup('<span color="green">'+
args[1]+
'</span>')
def connectSignals(self, click_signal, edit_signal, delete_signal):
"""connect widgets signals
Arguments:
- `click_signal`: toggle connection signal
- `edit_signal`: edit signal
- `delete_signal`: delete signal
"""
self.check_btn.connect("pressed", click_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.edit_btn.connect("clicked", edit_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.delete_btn.connect("clicked", delete_signal,
{"package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
class WifiItemHolder(gtk.ScrolledWindow):
"""holder for wifi connections
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
return data
return None
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
class MainInterface(object):
"""Imports main window glade
"""
def __init__(self):
"""import glade
"""
bind_glade_domain()
self._xml = glade.XML("ui/main.glade")
self._xml.signal_connect("on_window_main_destroy",
gtk.main_quit)
self._window = self._xml.get_widget("window_main")
self._holder = self._xml.get_widget("holder")
def getWindow(self):
"""returns window
"""
return self._window
def getHolder(self):
"""returns holder
"""
return self._holder
# --- Edit Window Sections (in ui: frame)
class EditSection(object):
def __init__(self, parent):
super(EditSection, self).__init__()
self.get = parent.get
self.signal_connect = parent._xml.signal_connect
self.parent = parent
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
def get_text_of(self, name):
"""gets text from widget in unicode"""
return unicode(self.get(name).get_text())
def collect_data(self, data):
"""collect data from ui and append datas to
given(data) dictionary"""
pass
class ProfileSection(EditSection):
def __init__(self, parent):
super(ProfileSection, self).__init__(parent)
def show_ui(self, data):
self.get("profilename").set_text(data[u"name"])
self.if_available_set(data, "device_name",
self.get("device_name_label").set_text)
self.device_id = data["device_id"]
#TODO:more than one device support
def collect_data(self, data):
super(ProfileSection, self).collect_data(data)
data["name"] = self.get_text_of("profilename")
data["device_id"] = unicode(self.device_id)
class NetworkSettingsSection(EditSection):
def __init__(self, parent):
super(NetworkSettingsSection, self).__init__(parent)
def _on_type_changed(self, widget):
if widget is self.get("dhcp_rb"):
self.set_manual_network(False)
else:
self.set_manual_network(True)
def set_manual_network(self, state):
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
# custom things
self.get("custom_gateway").set_sensitive(not state)
self.get("custom_address").set_sensitive(not state)
if not state:
self._on_custom_address(self.get("custom_address"))
self._on_custom_gateway(self.get("custom_gateway"))
def _on_custom_address(self, widget):
state = widget.get_active()
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
def _on_custom_gateway(self, widget):
state = widget.get_active()
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
def listen_signals(self):
self.signal_connect("on_dhcp_rb_clicked",
self._on_type_changed)
self.signal_connect("on_manual_rb_clicked",
self._on_type_changed)
self.signal_connect("on_custom_gateway_toggled",
self._on_custom_gateway)
self.signal_connect("on_custom_address_toggled",
self._on_custom_address)
def show_ui(self, data):
if data.has_key("net_mode"):
self.listen_signals()
if data["net_mode"] == "auto":
self.get("dhcp_rb").set_active(True)
self.set_manual_network(False)
if self.is_custom(data, "net_gateway"):
self.get("custom_gateway").set_active(True)
if self.is_custom(data, "net_address"):
self.get("custom_address").set_active(True)
else:
self.get("manual_rb").set_active(False)
self.set_manual_network(True)
self.if_available_set(data, "net_address",
self.get("address").set_text)
self.if_available_set(data, "net_mask",
self.get("networkmask").set_text)
self.if_available_set(data, "net_gateway",
self.get("gateway").set_text)
def is_custom(self, data, key):
if data.has_key(key):
if data[key] != "":
return True
return False
def collect_data(self, data):
super(NetworkSettingsSection, self).collect_data(data)
data["net_mode"] = u"auto"
data["net_address"] = u""
data["net_mask"] = u""
data["net_gateway"] = u""
if self.get("manual_rb").get_active():
data["net_mode"] = u"manual"
if self.get("address").state == gtk.STATE_NORMAL:
data["net_address"] = self.get_text_of("address")
data["net_mask"] = self.get_text_of("networkmask")
if self.get("gateway").state == gtk.STATE_NORMAL:
data["net_gateway"] = self.get_text_of("gateway")
class NameServerSection(EditSection):
def __init__(self, parent):
super(NameServerSection, self).__init__(parent)
def set_custom_name(self, state):
self.get("ns_custom_text").set_sensitive(state)
def _on_type_changed(self, widget):
if widget is self.get("ns_custom_rb"):
self.set_custom_name(True)
else:
self.set_custom_name(False)
def listen_signals(self):
self.signal_connect("on_ns_default_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_custom_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_auto_rb_clicked",
self._on_type_changed)
def show_ui(self, data):
if data.has_key("name_mode"):
self.listen_signals()
if data["name_mode"] == "default":
self.get("ns_default_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "auto":
self.get("ns_auto_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "custom":
self.get("ns_custom_rb").set_active(True)
self.set_custom_name(True)
self.if_available_set(data, "name_server",
self.get("ns_custom_text").set_text)
def collect_data(self, data):
super(NameServerSection, self).collect_data(data)
data["name_mode"] = u"default"
data["name_server"] = u""
if self.get("ns_auto_rb").get_active():
data["name_mode"] = u"auto"
if self.get("ns_custom_rb").get_active():
data["name_mode"] = u"custom"
data["name_server"] = self.get_text_of("ns_custom_text")
class WirelessSection(EditSection):
def __init__(self, parent):
super(WirelessSection, self).__init__(parent)
self.iface = parent.iface
self.package = parent._package
self.connection = parent._connection
# --- Password related
def show_password(self, state):
if not state:
self.get("hidepass_cb").hide()
self.get("pass_text").hide()
self.get("pass_lb").hide()
else:
self.get("hidepass_cb").show()
self.get("pass_text").show()
self.get("pass_lb").show()
def hide_password(self, widget):
visibility = not widget.get_active()
self.get("pass_text").set_visibility(visibility)
# end Password related
def scan(self, widget=None):
self.get("scan_btn").hide()
self.wifiitems.set_scanning(True)
self.iface.scanRemote(self.device , self.package, self.wifilist)
def security_types_changed(self, widget):
index = widget.get_active()
if index == 0:
self.show_password(False)
else:
self.show_password(True)
def listen_signals(self):
self.signal_connect("on_security_types_changed",
self.security_types_changed)
self.signal_connect("on_hidepass_cb_toggled",
self.hide_password)
def set_security_types_style(self):
##Security Type ComboBox
model = gtk.ListStore(str)
security_types = self.get("security_types")
security_types.set_model(model)
cell = gtk.CellRendererText()
security_types.pack_start(cell)
security_types.add_attribute(cell,'text',0)
def prepare_security_types(self, authType):
self.set_security_types_style()
noauth = _("No Authentication")
self._authMethods = [("none", noauth)]
append_to_types = self.get("security_types").append_text
append_to_types(noauth)
self.get("security_types").set_active(0)
index = 1
self.with_password = False
for name, desc in self.iface.authMethods(self.package):
append_to_types(desc)
self._authMethods.append((name, desc))
if name == authType:
self.get("security_types").set_active(index)
self.with_password = True
index += 1
def on_wifi_clicked(self, widget, callback_data):
data = callback_data["get_connection"]()
self.get("essid_text").set_text(data["remote"])
for index, method in enumerate(self._authMethods):
if method[0] == data["encryption"]:
self.get("security_types").set_active(index)
def wifilist(self, package, exception, args):
self.get("scan_btn").show()
self.signal_connect("on_scan_btn_clicked",
self.scan)
if not exception:
self.wifiitems.getConnections(args[0])
self.wifiitems.listen_change(self.on_wifi_clicked)
else:
print exception
def show_ui(self, data, caps):
self.listen_signals()
self.device = data["device_id"]
self.if_available_set(data, "remote",
self.get("essid_text").set_text)
modes = caps["modes"].split(",")
if "auth" in modes:
authType = self.iface.authType(self.package,
self.connection)
self.prepare_security_types(authType)
self.get("hidepass_cb").set_active(True)
if self.with_password:
authType = self.iface.authType(self.package,
self.connection)
authInfo = self.iface.authInfo(self.package,
self.connection)
authParams = self.iface.authParameters(self.package,
authType)
if len(authParams) == 1:
password = authInfo.values()[0]
self.get("pass_text").set_text(password)
elif len(authParams) > 1:
print "\nTODO:Dynamic WEP support"
self.show_password(self.with_password)
self.wifiitems = WifiItemHolder()
self.get("wireless_table").attach(self.wifiitems,
0, 1, 0, 3,
gtk.EXPAND|gtk.FILL,
gtk.EXPAND|gtk.FILL)
self.scan()
def collect_data(self, data):
super(WirelessSection, self).collect_data(data)
data["remote"] = self.get_text_of("essid_text")
data["apmac"] = u"" #??? what is it
#Security
data["auth"] = unicode(self._authMethods[
self.get("security_types").get_active()][0])
if data["auth"] != u"none":
params = self.iface.authParameters("wireless_tools",
data["auth"])
- data["auth_%s" % param]
if len(params) == 1:
key = "auth_%s" % params[0][0]
- data[key] = self.get_text_of("pass_txt")
+ data[key] = self.get_text_of("pass_text")
else:
print "TODO:Dynamic WEP Support"
# end Edit Window Sections
class EditInterface(object):
"""Imports edit window glade
"""
def __init__(self, package, connection):
"""init
Arguments:
- `package`:
- `connection`:
"""
bind_glade_domain()
self.iface = NetworkIface()
self._package = package
self._connection = connection
self._xml = glade.XML("ui/edit.glade")
self.get = self._xml.get_widget
self.listen_signals()
self.insertData()
def apply(self, widget):
data = self.collect_data()
- print data
try:
- pass
self.iface.updateConnection(self._package,
data["name"],
data)
except Exception, e:
print "Exception:", unicode(e)
if not self.name == data["name"]:
self.iface.deleteConnection(self._package, self.name)
if self.is_up:
self.iface.connect(self._package, self.name)
self.getWindow().destroy()
def cancel(self, widget):
self.getWindow().destroy()
def listen_signals(self):
self._xml.signal_connect("apply_btn_clicked",
self.apply)
self._xml.signal_connect("cancel_btn_clicked",
self.cancel)
def insertData(self):
"""show preferences
"""
data = self.iface.info(self._package,
self._connection)
self.name = data["name"]
self.is_up = False
if data.has_key("state"):
if data["state"][0:2] == "up":
self.is_up = True
#Profile Frame
self.profile_frame = ProfileSection(self)
self.profile_frame.show_ui(data)
#Network Settings Frame
self.network_frame = NetworkSettingsSection(self)
self.network_frame.show_ui(data)
#Name Servers Frame
self.name_frame = NameServerSection(self)
self.name_frame.show_ui(data)
# Wireless Frame
if self._package == "wireless_tools":
caps = self.iface.capabilities(self._package)
self.wireless_frame = WirelessSection(self)
self.wireless_frame.show_ui(data, caps)
else:
self.get("wireless_frame").hide()
def collect_data(self):
data = {}
self.profile_frame.collect_data(data)
self.network_frame.collect_data(data)
self.name_frame.collect_data(data)
if self._package == "wireless_tools":
self.wireless_frame.collect_data(data)
return data
def getWindow(self):
"""returns window
"""
return self.get("window_edit")
|
rdno/pardus-network-manager-gtk
|
ef62862b9c7309bbf40a56d1da2790a12f21fb6c
|
ui fix
|
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index 323add0..63772a3 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,543 +1,542 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
"""A special widget contains connection related stuff
"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
self._createUI()
def _createUI(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.setMode(self._state.split(' '))
def setMode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- `args`: state, detail
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
self._info.set_markup('<span color="green">'+
args[1]+
'</span>')
def connectSignals(self, click_signal, edit_signal, delete_signal):
"""connect widgets signals
Arguments:
- `click_signal`: toggle connection signal
- `edit_signal`: edit signal
- `delete_signal`: delete signal
"""
self.check_btn.connect("pressed", click_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.edit_btn.connect("clicked", edit_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.delete_btn.connect("clicked", delete_signal,
{"package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
class WifiItemHolder(gtk.ScrolledWindow):
"""holder for wifi connections
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
return data
return None
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
class MainInterface(object):
"""Imports main window glade
"""
def __init__(self):
"""import glade
"""
bind_glade_domain()
self._xml = glade.XML("ui/main.glade")
self._xml.signal_connect("on_window_main_destroy",
gtk.main_quit)
self._window = self._xml.get_widget("window_main")
self._holder = self._xml.get_widget("holder")
def getWindow(self):
"""returns window
"""
return self._window
def getHolder(self):
"""returns holder
"""
return self._holder
# --- Edit Window Sections (in ui: frame)
class EditSection(object):
def __init__(self, parent):
super(EditSection, self).__init__()
self.get = parent.get
self.signal_connect = parent._xml.signal_connect
self.parent = parent
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
def get_text_of(self, name):
"""gets text from widget in unicode"""
return unicode(self.get(name).get_text())
def collect_data(self, data):
"""collect data from ui and append datas to
given(data) dictionary"""
pass
class ProfileSection(EditSection):
def __init__(self, parent):
super(ProfileSection, self).__init__(parent)
def show_ui(self, data):
self.get("profilename").set_text(data[u"name"])
self.if_available_set(data, "device_name",
self.get("device_name_label").set_text)
self.device_id = data["device_id"]
#TODO:more than one device support
def collect_data(self, data):
super(ProfileSection, self).collect_data(data)
data["name"] = self.get_text_of("profilename")
data["device_id"] = unicode(self.device_id)
class NetworkSettingsSection(EditSection):
def __init__(self, parent):
super(NetworkSettingsSection, self).__init__(parent)
def _on_type_changed(self, widget):
if widget is self.get("dhcp_rb"):
self.set_manual_network(False)
else:
self.set_manual_network(True)
def set_manual_network(self, state):
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
# custom things
self.get("custom_gateway").set_sensitive(not state)
self.get("custom_address").set_sensitive(not state)
if not state:
self._on_custom_address(self.get("custom_address"))
self._on_custom_gateway(self.get("custom_gateway"))
def _on_custom_address(self, widget):
state = widget.get_active()
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
def _on_custom_gateway(self, widget):
state = widget.get_active()
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
def listen_signals(self):
self.signal_connect("on_dhcp_rb_clicked",
self._on_type_changed)
self.signal_connect("on_manual_rb_clicked",
self._on_type_changed)
self.signal_connect("on_custom_gateway_toggled",
self._on_custom_gateway)
self.signal_connect("on_custom_address_toggled",
self._on_custom_address)
def show_ui(self, data):
if data.has_key("net_mode"):
self.listen_signals()
if data["net_mode"] == "auto":
self.get("dhcp_rb").set_active(True)
self.set_manual_network(False)
if self.is_custom(data, "net_gateway"):
self.get("custom_gateway").set_active(True)
if self.is_custom(data, "net_address"):
self.get("custom_address").set_active(True)
else:
self.get("manual_rb").set_active(False)
self.set_manual_network(True)
self.if_available_set(data, "net_address",
self.get("address").set_text)
self.if_available_set(data, "net_mask",
self.get("networkmask").set_text)
self.if_available_set(data, "net_gateway",
self.get("gateway").set_text)
def is_custom(self, data, key):
if data.has_key(key):
if data[key] != "":
return True
return False
def collect_data(self, data):
super(NetworkSettingsSection, self).collect_data(data)
data["net_mode"] = u"auto"
data["net_address"] = u""
data["net_mask"] = u""
data["net_gateway"] = u""
if self.get("manual_rb").get_active():
data["net_mode"] = u"manual"
if self.get("address").state == gtk.STATE_NORMAL:
data["net_address"] = self.get_text_of("address")
data["net_mask"] = self.get_text_of("networkmask")
if self.get("gateway").state == gtk.STATE_NORMAL:
data["net_gateway"] = self.get_text_of("gateway")
class NameServerSection(EditSection):
def __init__(self, parent):
super(NameServerSection, self).__init__(parent)
def set_custom_name(self, state):
self.get("ns_custom_text").set_sensitive(state)
def _on_type_changed(self, widget):
if widget is self.get("ns_custom_rb"):
self.set_custom_name(True)
else:
self.set_custom_name(False)
def listen_signals(self):
self.signal_connect("on_ns_default_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_custom_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_auto_rb_clicked",
self._on_type_changed)
def show_ui(self, data):
if data.has_key("name_mode"):
self.listen_signals()
if data["name_mode"] == "default":
self.get("ns_default_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "auto":
self.get("ns_auto_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "custom":
self.get("ns_custom_rb").set_active(True)
self.set_custom_name(True)
self.if_available_set(data, "name_server",
self.get("ns_custom_text").set_text)
def collect_data(self, data):
super(NameServerSection, self).collect_data(data)
data["name_mode"] = u"default"
data["name_server"] = u""
if self.get("ns_auto_rb").get_active():
data["name_mode"] = u"auto"
if self.get("ns_custom_rb").get_active():
data["name_mode"] = u"custom"
data["name_server"] = self.get_text_of("ns_custom_text")
class WirelessSection(EditSection):
def __init__(self, parent):
super(WirelessSection, self).__init__(parent)
self.iface = parent.iface
self.package = parent._package
self.connection = parent._connection
# --- Password related
def show_password(self, state):
if not state:
self.get("hidepass_cb").hide()
self.get("pass_text").hide()
self.get("pass_lb").hide()
else:
self.get("hidepass_cb").show()
self.get("pass_text").show()
self.get("pass_lb").show()
def hide_password(self, widget):
visibility = not widget.get_active()
self.get("pass_text").set_visibility(visibility)
# end Password related
def scan(self, widget=None):
self.get("scan_btn").hide()
self.wifiitems.set_scanning(True)
self.iface.scanRemote(self.device , self.package, self.wifilist)
def security_types_changed(self, widget):
index = widget.get_active()
if index == 0:
self.show_password(False)
else:
self.show_password(True)
def listen_signals(self):
self.signal_connect("on_security_types_changed",
self.security_types_changed)
self.signal_connect("on_hidepass_cb_toggled",
self.hide_password)
def set_security_types_style(self):
##Security Type ComboBox
model = gtk.ListStore(str)
security_types = self.get("security_types")
security_types.set_model(model)
cell = gtk.CellRendererText()
security_types.pack_start(cell)
security_types.add_attribute(cell,'text',0)
def prepare_security_types(self, authType):
self.set_security_types_style()
noauth = _("No Authentication")
self._authMethods = [("none", noauth)]
append_to_types = self.get("security_types").append_text
append_to_types(noauth)
self.get("security_types").set_active(0)
index = 1
self.with_password = False
for name, desc in self.iface.authMethods(self.package):
append_to_types(desc)
self._authMethods.append((name, desc))
if name == authType:
self.get("security_types").set_active(index)
self.with_password = True
index += 1
def on_wifi_clicked(self, widget, callback_data):
data = callback_data["get_connection"]()
- # data["remote"] = isim, data["encryption"]
self.get("essid_text").set_text(data["remote"])
for index, method in enumerate(self._authMethods):
if method[0] == data["encryption"]:
self.get("security_types").set_active(index)
def wifilist(self, package, exception, args):
self.get("scan_btn").show()
self.signal_connect("on_scan_btn_clicked",
self.scan)
if not exception:
self.wifiitems.getConnections(args[0])
self.wifiitems.listen_change(self.on_wifi_clicked)
else:
print exception
def show_ui(self, data, caps):
self.listen_signals()
self.device = data["device_id"]
self.if_available_set(data, "remote",
self.get("essid_text").set_text)
modes = caps["modes"].split(",")
if "auth" in modes:
authType = self.iface.authType(self.package,
self.connection)
self.prepare_security_types(authType)
self.get("hidepass_cb").set_active(True)
if self.with_password:
authType = self.iface.authType(self.package,
self.connection)
authInfo = self.iface.authInfo(self.package,
self.connection)
authParams = self.iface.authParameters(self.package,
authType)
if len(authParams) == 1:
password = authInfo.values()[0]
self.get("pass_text").set_text(password)
elif len(authParams) > 1:
print "\nTODO:Dynamic WEP support"
self.show_password(self.with_password)
self.wifiitems = WifiItemHolder()
self.get("wireless_table").attach(self.wifiitems,
- 0, 1, 0, 4,
+ 0, 1, 0, 3,
gtk.EXPAND|gtk.FILL,
gtk.EXPAND|gtk.FILL)
self.scan()
def collect_data(self, data):
super(WirelessSection, self).collect_data(data)
data["remote"] = self.get_text_of("essid_text")
data["apmac"] = u"" #??? what is it
#Security
data["auth"] = unicode(self._authMethods[
self.get("security_types").get_active()][0])
if data["auth"] != u"none":
params = self.iface.authParameters("wireless_tools",
data["auth"])
data["auth_%s" % param]
if len(params) == 1:
key = "auth_%s" % params[0][0]
data[key] = self.get_text_of("pass_txt")
else:
print "TODO:Dynamic WEP Support"
# end Edit Window Sections
class EditInterface(object):
"""Imports edit window glade
"""
def __init__(self, package, connection):
"""init
Arguments:
- `package`:
- `connection`:
"""
bind_glade_domain()
self.iface = NetworkIface()
self._package = package
self._connection = connection
self._xml = glade.XML("ui/edit.glade")
self.get = self._xml.get_widget
self.listen_signals()
self.insertData()
def apply(self, widget):
data = self.collect_data()
print data
try:
pass
self.iface.updateConnection(self._package,
data["name"],
data)
except Exception, e:
print "Exception:", unicode(e)
if not self.name == data["name"]:
self.iface.deleteConnection(self._package, self.name)
if self.is_up:
self.iface.connect(self._package, self.name)
self.getWindow().destroy()
def cancel(self, widget):
self.getWindow().destroy()
def listen_signals(self):
self._xml.signal_connect("apply_btn_clicked",
self.apply)
self._xml.signal_connect("cancel_btn_clicked",
self.cancel)
def insertData(self):
"""show preferences
"""
data = self.iface.info(self._package,
self._connection)
self.name = data["name"]
self.is_up = False
if data.has_key("state"):
if data["state"][0:2] == "up":
self.is_up = True
#Profile Frame
self.profile_frame = ProfileSection(self)
self.profile_frame.show_ui(data)
#Network Settings Frame
self.network_frame = NetworkSettingsSection(self)
self.network_frame.show_ui(data)
#Name Servers Frame
self.name_frame = NameServerSection(self)
self.name_frame.show_ui(data)
# Wireless Frame
if self._package == "wireless_tools":
caps = self.iface.capabilities(self._package)
self.wireless_frame = WirelessSection(self)
self.wireless_frame.show_ui(data, caps)
else:
self.get("wireless_frame").hide()
def collect_data(self):
data = {}
self.profile_frame.collect_data(data)
self.network_frame.collect_data(data)
self.name_frame.collect_data(data)
if self._package == "wireless_tools":
self.wireless_frame.collect_data(data)
return data
def getWindow(self):
"""returns window
"""
return self.get("window_edit")
|
rdno/pardus-network-manager-gtk
|
d5f046568e83bb39abf6adc2c139b9d0c53591b8
|
removed change password button;added changing wireless support
|
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index 0541d29..323add0 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,560 +1,543 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
"""A special widget contains connection related stuff
"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
self._createUI()
def _createUI(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.setMode(self._state.split(' '))
def setMode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- `args`: state, detail
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
self._info.set_markup('<span color="green">'+
args[1]+
'</span>')
def connectSignals(self, click_signal, edit_signal, delete_signal):
"""connect widgets signals
Arguments:
- `click_signal`: toggle connection signal
- `edit_signal`: edit signal
- `delete_signal`: delete signal
"""
self.check_btn.connect("pressed", click_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.edit_btn.connect("clicked", edit_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.delete_btn.connect("clicked", delete_signal,
{"package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
class WifiItemHolder(gtk.ScrolledWindow):
"""holder for wifi connections
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
return data
return None
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
class MainInterface(object):
"""Imports main window glade
"""
def __init__(self):
"""import glade
"""
bind_glade_domain()
self._xml = glade.XML("ui/main.glade")
self._xml.signal_connect("on_window_main_destroy",
gtk.main_quit)
self._window = self._xml.get_widget("window_main")
self._holder = self._xml.get_widget("holder")
def getWindow(self):
"""returns window
"""
return self._window
def getHolder(self):
"""returns holder
"""
return self._holder
# --- Edit Window Sections (in ui: frame)
class EditSection(object):
def __init__(self, parent):
super(EditSection, self).__init__()
self.get = parent.get
self.signal_connect = parent._xml.signal_connect
self.parent = parent
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
def get_text_of(self, name):
"""gets text from widget in unicode"""
return unicode(self.get(name).get_text())
def collect_data(self, data):
"""collect data from ui and append datas to
given(data) dictionary"""
pass
class ProfileSection(EditSection):
def __init__(self, parent):
super(ProfileSection, self).__init__(parent)
def show_ui(self, data):
self.get("profilename").set_text(data[u"name"])
self.if_available_set(data, "device_name",
self.get("device_name_label").set_text)
self.device_id = data["device_id"]
#TODO:more than one device support
def collect_data(self, data):
super(ProfileSection, self).collect_data(data)
data["name"] = self.get_text_of("profilename")
data["device_id"] = unicode(self.device_id)
class NetworkSettingsSection(EditSection):
def __init__(self, parent):
super(NetworkSettingsSection, self).__init__(parent)
def _on_type_changed(self, widget):
if widget is self.get("dhcp_rb"):
self.set_manual_network(False)
else:
self.set_manual_network(True)
def set_manual_network(self, state):
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
# custom things
self.get("custom_gateway").set_sensitive(not state)
self.get("custom_address").set_sensitive(not state)
if not state:
self._on_custom_address(self.get("custom_address"))
self._on_custom_gateway(self.get("custom_gateway"))
def _on_custom_address(self, widget):
state = widget.get_active()
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
def _on_custom_gateway(self, widget):
state = widget.get_active()
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
def listen_signals(self):
self.signal_connect("on_dhcp_rb_clicked",
self._on_type_changed)
self.signal_connect("on_manual_rb_clicked",
self._on_type_changed)
self.signal_connect("on_custom_gateway_toggled",
self._on_custom_gateway)
self.signal_connect("on_custom_address_toggled",
self._on_custom_address)
def show_ui(self, data):
if data.has_key("net_mode"):
self.listen_signals()
if data["net_mode"] == "auto":
self.get("dhcp_rb").set_active(True)
self.set_manual_network(False)
if self.is_custom(data, "net_gateway"):
self.get("custom_gateway").set_active(True)
if self.is_custom(data, "net_address"):
self.get("custom_address").set_active(True)
else:
self.get("manual_rb").set_active(False)
self.set_manual_network(True)
self.if_available_set(data, "net_address",
self.get("address").set_text)
self.if_available_set(data, "net_mask",
self.get("networkmask").set_text)
self.if_available_set(data, "net_gateway",
self.get("gateway").set_text)
def is_custom(self, data, key):
if data.has_key(key):
if data[key] != "":
return True
return False
def collect_data(self, data):
super(NetworkSettingsSection, self).collect_data(data)
data["net_mode"] = u"auto"
data["net_address"] = u""
data["net_mask"] = u""
data["net_gateway"] = u""
if self.get("manual_rb").get_active():
data["net_mode"] = u"manual"
if self.get("address").state == gtk.STATE_NORMAL:
data["net_address"] = self.get_text_of("address")
data["net_mask"] = self.get_text_of("networkmask")
if self.get("gateway").state == gtk.STATE_NORMAL:
data["net_gateway"] = self.get_text_of("gateway")
class NameServerSection(EditSection):
def __init__(self, parent):
super(NameServerSection, self).__init__(parent)
def set_custom_name(self, state):
self.get("ns_custom_text").set_sensitive(state)
def _on_type_changed(self, widget):
if widget is self.get("ns_custom_rb"):
self.set_custom_name(True)
else:
self.set_custom_name(False)
def listen_signals(self):
self.signal_connect("on_ns_default_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_custom_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_auto_rb_clicked",
self._on_type_changed)
def show_ui(self, data):
if data.has_key("name_mode"):
self.listen_signals()
if data["name_mode"] == "default":
self.get("ns_default_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "auto":
self.get("ns_auto_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "custom":
self.get("ns_custom_rb").set_active(True)
self.set_custom_name(True)
self.if_available_set(data, "name_server",
self.get("ns_custom_text").set_text)
def collect_data(self, data):
super(NameServerSection, self).collect_data(data)
data["name_mode"] = u"default"
data["name_server"] = u""
if self.get("ns_auto_rb").get_active():
data["name_mode"] = u"auto"
if self.get("ns_custom_rb").get_active():
data["name_mode"] = u"custom"
data["name_server"] = self.get_text_of("ns_custom_text")
class WirelessSection(EditSection):
- def __init__(self, parent, password_state="hidden"):
+ def __init__(self, parent):
super(WirelessSection, self).__init__(parent)
- self.password_state = password_state
self.iface = parent.iface
self.package = parent._package
self.connection = parent._connection
# --- Password related
def show_password(self, state):
- if (state == False) | (state == "hidden"):
+ if not state:
self.get("hidepass_cb").hide()
self.get("pass_text").hide()
self.get("pass_lb").hide()
- elif state == True:
+ else:
self.get("hidepass_cb").show()
self.get("pass_text").show()
self.get("pass_lb").show()
- if state == "hidden":
- self.get("changepass_btn").show()
- else:
- self.get("changepass_btn").hide()
- def change_password(self, widget=None):
- self.show_password(True)
- print "heyya"
- authType = self.iface.authType(self.package,
- self.connection)
- authInfo = self.iface.authInfo(self.package,
- self.connection)
- authParams = self.iface.authParameters(self.package,
- authType)
- if len(authParams) == 1:
- password = authInfo.values()[0]
- self.get("pass_text").set_text(password)
- self.get("hidepass_cb").set_active(True)
- elif len(authParams) > 1:
- print "\nTODO:learn what is securityDialog"
- print "--> at svn-24515 / base.py line:474\n"
def hide_password(self, widget):
visibility = not widget.get_active()
self.get("pass_text").set_visibility(visibility)
# end Password related
def scan(self, widget=None):
self.get("scan_btn").hide()
self.wifiitems.set_scanning(True)
self.iface.scanRemote(self.device , self.package, self.wifilist)
def security_types_changed(self, widget):
index = widget.get_active()
if index == 0:
self.show_password(False)
else:
self.show_password(True)
def listen_signals(self):
self.signal_connect("on_security_types_changed",
self.security_types_changed)
- #Password related
- self.signal_connect("on_changepass_btn_clicked",
- self.change_password)
self.signal_connect("on_hidepass_cb_toggled",
self.hide_password)
def set_security_types_style(self):
##Security Type ComboBox
model = gtk.ListStore(str)
security_types = self.get("security_types")
security_types.set_model(model)
cell = gtk.CellRendererText()
security_types.pack_start(cell)
security_types.add_attribute(cell,'text',0)
def prepare_security_types(self, authType):
self.set_security_types_style()
noauth = _("No Authentication")
self._authMethods = [("none", noauth)]
append_to_types = self.get("security_types").append_text
append_to_types(noauth)
self.get("security_types").set_active(0)
index = 1
self.with_password = False
for name, desc in self.iface.authMethods(self.package):
append_to_types(desc)
self._authMethods.append((name, desc))
if name == authType:
self.get("security_types").set_active(index)
self.with_password = True
index += 1
def on_wifi_clicked(self, widget, callback_data):
data = callback_data["get_connection"]()
# data["remote"] = isim, data["encryption"]
- print data
+ self.get("essid_text").set_text(data["remote"])
+ for index, method in enumerate(self._authMethods):
+ if method[0] == data["encryption"]:
+ self.get("security_types").set_active(index)
def wifilist(self, package, exception, args):
self.get("scan_btn").show()
self.signal_connect("on_scan_btn_clicked",
self.scan)
if not exception:
self.wifiitems.getConnections(args[0])
self.wifiitems.listen_change(self.on_wifi_clicked)
else:
print exception
def show_ui(self, data, caps):
self.listen_signals()
self.device = data["device_id"]
self.if_available_set(data, "remote",
self.get("essid_text").set_text)
modes = caps["modes"].split(",")
if "auth" in modes:
- authType = self.iface.authType(self.parent._package,
- self.parent._connection)
+ authType = self.iface.authType(self.package,
+ self.connection)
self.prepare_security_types(authType)
self.get("hidepass_cb").set_active(True)
if self.with_password:
- self.show_password(self.password_state)
- #if self.get("security_types").get_active() == 0:#No Auth
- # self.show_password(False)
+ authType = self.iface.authType(self.package,
+ self.connection)
+ authInfo = self.iface.authInfo(self.package,
+ self.connection)
+ authParams = self.iface.authParameters(self.package,
+ authType)
+ if len(authParams) == 1:
+ password = authInfo.values()[0]
+ self.get("pass_text").set_text(password)
+ elif len(authParams) > 1:
+ print "\nTODO:Dynamic WEP support"
+ self.show_password(self.with_password)
self.wifiitems = WifiItemHolder()
self.get("wireless_table").attach(self.wifiitems,
0, 1, 0, 4,
gtk.EXPAND|gtk.FILL,
gtk.EXPAND|gtk.FILL)
self.scan()
def collect_data(self, data):
super(WirelessSection, self).collect_data(data)
data["remote"] = self.get_text_of("essid_text")
data["apmac"] = u"" #??? what is it
#Security
data["auth"] = unicode(self._authMethods[
self.get("security_types").get_active()][0])
if data["auth"] != u"none":
params = self.iface.authParameters("wireless_tools",
data["auth"])
+ data["auth_%s" % param]
if len(params) == 1:
key = "auth_%s" % params[0][0]
- if self.get("pass_text").props.visible:
- data[key] = self.get_text_of("pass_text")
- else:
- info = self.iface.authInfo(self.parent._package,
- self.parent._connection)
- data[key] = info.values()[0]
+ data[key] = self.get_text_of("pass_txt")
else:
- print "TODO:more than one security params"
- print "at collect_data\n"
+ print "TODO:Dynamic WEP Support"
# end Edit Window Sections
class EditInterface(object):
"""Imports edit window glade
"""
def __init__(self, package, connection):
"""init
Arguments:
- `package`:
- `connection`:
"""
bind_glade_domain()
self.iface = NetworkIface()
self._package = package
self._connection = connection
self._xml = glade.XML("ui/edit.glade")
self.get = self._xml.get_widget
self.listen_signals()
self.insertData()
def apply(self, widget):
data = self.collect_data()
print data
try:
pass
self.iface.updateConnection(self._package,
data["name"],
data)
except Exception, e:
print "Exception:", unicode(e)
if not self.name == data["name"]:
self.iface.deleteConnection(self._package, self.name)
if self.is_up:
self.iface.connect(self._package, self.name)
self.getWindow().destroy()
def cancel(self, widget):
self.getWindow().destroy()
def listen_signals(self):
self._xml.signal_connect("apply_btn_clicked",
self.apply)
self._xml.signal_connect("cancel_btn_clicked",
self.cancel)
def insertData(self):
"""show preferences
"""
data = self.iface.info(self._package,
self._connection)
self.name = data["name"]
self.is_up = False
if data.has_key("state"):
if data["state"][0:2] == "up":
self.is_up = True
#Profile Frame
self.profile_frame = ProfileSection(self)
self.profile_frame.show_ui(data)
#Network Settings Frame
self.network_frame = NetworkSettingsSection(self)
self.network_frame.show_ui(data)
#Name Servers Frame
self.name_frame = NameServerSection(self)
self.name_frame.show_ui(data)
# Wireless Frame
if self._package == "wireless_tools":
caps = self.iface.capabilities(self._package)
self.wireless_frame = WirelessSection(self)
self.wireless_frame.show_ui(data, caps)
else:
self.get("wireless_frame").hide()
def collect_data(self):
data = {}
self.profile_frame.collect_data(data)
self.network_frame.collect_data(data)
self.name_frame.collect_data(data)
if self._package == "wireless_tools":
self.wireless_frame.collect_data(data)
return data
def getWindow(self):
"""returns window
"""
return self.get("window_edit")
diff --git a/ui/edit.glade b/ui/edit.glade
index 8169888..7166e11 100644
--- a/ui/edit.glade
+++ b/ui/edit.glade
@@ -1,590 +1,570 @@
<?xml version="1.0"?>
<glade-interface>
<!-- interface-requires gtk+ 2.16 -->
<!-- interface-naming-policy project-wide -->
<widget class="GtkWindow" id="window_edit">
<property name="title" translatable="yes" comments="Edit Cable Settings Window Title">Edit Connection</property>
<property name="default_width">640</property>
<child>
<widget class="GtkVBox" id="vbox1">
<property name="visible">True</property>
<property name="orientation">vertical</property>
<property name="spacing">6</property>
<child>
<widget class="GtkFrame" id="profile_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment1">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkHBox" id="hbox1">
<property name="visible">True</property>
<property name="spacing">2</property>
<child>
<widget class="GtkLabel" id="label3">
<property name="visible">True</property>
<property name="label" translatable="yes">Profile Name:</property>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="profilename">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="device_name_label">
<property name="visible">True</property>
<property name="xalign">0</property>
<property name="label">device name goes here </property>
<property name="use_markup">True</property>
<property name="ellipsize">middle</property>
</widget>
<packing>
<property name="pack_type">end</property>
<property name="position">2</property>
</packing>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label1">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Profile</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkFrame" id="wireless_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment4">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkTable" id="wireless_table">
<property name="visible">True</property>
- <property name="n_rows">5</property>
+ <property name="n_rows">4</property>
<property name="n_columns">3</property>
<child>
<widget class="GtkButton" id="scan_btn">
<property name="label" translatable="yes">Scan</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<signal name="clicked" handler="on_scan_btn_clicked"/>
</widget>
<packing>
- <property name="top_attach">4</property>
- <property name="bottom_attach">5</property>
+ <property name="top_attach">3</property>
+ <property name="bottom_attach">4</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="label9">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Security Type:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="pass_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Password:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options">GTK_FILL</property>
</packing>
</child>
<child>
<widget class="GtkComboBox" id="security_types">
<property name="visible">True</property>
<signal name="changed" handler="on_security_types_changed"/>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="pass_text">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
<property name="invisible_char_set">True</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkCheckButton" id="hidepass_cb">
<property name="label" translatable="yes">Hide Password</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="draw_indicator">True</property>
<signal name="toggled" handler="on_hidepass_cb_toggled"/>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">3</property>
<property name="top_attach">3</property>
<property name="bottom_attach">4</property>
<property name="x_options"></property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="label5">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">ESSID:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="essid_text">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
- <child>
- <widget class="GtkButton" id="changepass_btn">
- <property name="label" translatable="yes">Change Password</property>
- <property name="visible">True</property>
- <property name="can_focus">True</property>
- <property name="receives_default">True</property>
- <signal name="clicked" handler="on_changepass_btn_clicked"/>
- </widget>
- <packing>
- <property name="left_attach">1</property>
- <property name="right_attach">3</property>
- <property name="top_attach">4</property>
- <property name="bottom_attach">5</property>
- <property name="x_options"></property>
- <property name="y_options"></property>
- </packing>
- </child>
- <child>
- <placeholder/>
- </child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label8">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Wireless</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkFrame" id="network_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment2">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkVBox" id="vbox2">
<property name="visible">True</property>
<property name="orientation">vertical</property>
<property name="spacing">5</property>
<child>
<widget class="GtkRadioButton" id="dhcp_rb">
<property name="label" translatable="yes">Use DHCP</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<signal name="clicked" handler="on_dhcp_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkTable" id="table2">
<property name="visible">True</property>
<property name="n_rows">3</property>
<property name="n_columns">4</property>
<property name="row_spacing">5</property>
<child>
<widget class="GtkRadioButton" id="manual_rb">
<property name="label" translatable="yes">Use Manual Settings</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<property name="group">dhcp_rb</property>
<signal name="clicked" handler="on_manual_rb_clicked"/>
</widget>
</child>
<child>
<widget class="GtkLabel" id="address_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Address:</property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="networkmask_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Network Mask:</property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="gateway_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Default Gateway:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
<property name="y_options">GTK_EXPAND</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="address">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="networkmask">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="gateway">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
</packing>
</child>
<child>
<widget class="GtkCheckButton" id="custom_address">
<property name="label" translatable="yes">Custom</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="draw_indicator">True</property>
<signal name="toggled" handler="on_custom_address_toggled"/>
</widget>
<packing>
<property name="left_attach">3</property>
<property name="right_attach">4</property>
</packing>
</child>
<child>
<widget class="GtkCheckButton" id="custom_gateway">
<property name="label" translatable="yes">Custom</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="draw_indicator">True</property>
<signal name="toggled" handler="on_custom_gateway_toggled"/>
</widget>
<packing>
<property name="left_attach">3</property>
<property name="right_attach">4</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
</packing>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">1</property>
</packing>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label2">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Network Settings</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">2</property>
</packing>
</child>
<child>
<widget class="GtkFrame" id="ns_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment3">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkHBox" id="hbox2">
<property name="visible">True</property>
<property name="spacing">5</property>
<child>
<widget class="GtkRadioButton" id="ns_default_rb">
<property name="label" translatable="yes">Default</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<signal name="clicked" handler="on_ns_default_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkRadioButton" id="ns_auto_rb">
<property name="label" translatable="yes">Automatic</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<property name="group">ns_default_rb</property>
<signal name="clicked" handler="on_ns_auto_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkRadioButton" id="ns_custom_rb">
<property name="label" translatable="yes">Custom</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="draw_indicator">True</property>
<property name="group">ns_default_rb</property>
<signal name="clicked" handler="on_ns_custom_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">2</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="ns_custom_text">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="editable">False</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="position">3</property>
</packing>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label4">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Name Servers</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">3</property>
</packing>
</child>
<child>
<widget class="GtkHBox" id="hbox3">
<property name="visible">True</property>
<property name="spacing">5</property>
<child>
<widget class="GtkButton" id="cancel_btn">
<property name="label" translatable="yes">Cancel</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="use_underline">True</property>
<signal name="clicked" handler="cancel_btn_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="pack_type">end</property>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkButton" id="apply_btn">
<property name="label" translatable="yes">Apply</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="use_underline">True</property>
<signal name="clicked" handler="apply_btn_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="pack_type">end</property>
<property name="position">0</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="pack_type">end</property>
<property name="position">4</property>
</packing>
</child>
</widget>
</child>
</widget>
</glade-interface>
|
rdno/pardus-network-manager-gtk
|
556b626800c4456c412ee3e5884e757fb914b44f
|
listen security types change
|
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index 65d891c..0541d29 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,550 +1,560 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
"""A special widget contains connection related stuff
"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
self._createUI()
def _createUI(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.setMode(self._state.split(' '))
def setMode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- `args`: state, detail
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
self._info.set_markup('<span color="green">'+
args[1]+
'</span>')
def connectSignals(self, click_signal, edit_signal, delete_signal):
"""connect widgets signals
Arguments:
- `click_signal`: toggle connection signal
- `edit_signal`: edit signal
- `delete_signal`: delete signal
"""
self.check_btn.connect("pressed", click_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.edit_btn.connect("clicked", edit_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.delete_btn.connect("clicked", delete_signal,
{"package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
class WifiItemHolder(gtk.ScrolledWindow):
"""holder for wifi connections
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
- else:
- data = None
- return data
+ return data
+ return None
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
class MainInterface(object):
"""Imports main window glade
"""
def __init__(self):
"""import glade
"""
bind_glade_domain()
self._xml = glade.XML("ui/main.glade")
self._xml.signal_connect("on_window_main_destroy",
gtk.main_quit)
self._window = self._xml.get_widget("window_main")
self._holder = self._xml.get_widget("holder")
def getWindow(self):
"""returns window
"""
return self._window
def getHolder(self):
"""returns holder
"""
return self._holder
# --- Edit Window Sections (in ui: frame)
class EditSection(object):
def __init__(self, parent):
super(EditSection, self).__init__()
self.get = parent.get
self.signal_connect = parent._xml.signal_connect
self.parent = parent
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
def get_text_of(self, name):
"""gets text from widget in unicode"""
return unicode(self.get(name).get_text())
def collect_data(self, data):
"""collect data from ui and append datas to
given(data) dictionary"""
pass
class ProfileSection(EditSection):
def __init__(self, parent):
super(ProfileSection, self).__init__(parent)
def show_ui(self, data):
self.get("profilename").set_text(data[u"name"])
self.if_available_set(data, "device_name",
self.get("device_name_label").set_text)
self.device_id = data["device_id"]
#TODO:more than one device support
def collect_data(self, data):
super(ProfileSection, self).collect_data(data)
data["name"] = self.get_text_of("profilename")
data["device_id"] = unicode(self.device_id)
class NetworkSettingsSection(EditSection):
def __init__(self, parent):
super(NetworkSettingsSection, self).__init__(parent)
def _on_type_changed(self, widget):
if widget is self.get("dhcp_rb"):
self.set_manual_network(False)
else:
self.set_manual_network(True)
def set_manual_network(self, state):
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
# custom things
self.get("custom_gateway").set_sensitive(not state)
self.get("custom_address").set_sensitive(not state)
if not state:
self._on_custom_address(self.get("custom_address"))
self._on_custom_gateway(self.get("custom_gateway"))
def _on_custom_address(self, widget):
state = widget.get_active()
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
def _on_custom_gateway(self, widget):
state = widget.get_active()
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
def listen_signals(self):
self.signal_connect("on_dhcp_rb_clicked",
self._on_type_changed)
self.signal_connect("on_manual_rb_clicked",
self._on_type_changed)
self.signal_connect("on_custom_gateway_toggled",
self._on_custom_gateway)
self.signal_connect("on_custom_address_toggled",
self._on_custom_address)
def show_ui(self, data):
if data.has_key("net_mode"):
self.listen_signals()
if data["net_mode"] == "auto":
self.get("dhcp_rb").set_active(True)
self.set_manual_network(False)
if self.is_custom(data, "net_gateway"):
self.get("custom_gateway").set_active(True)
if self.is_custom(data, "net_address"):
self.get("custom_address").set_active(True)
else:
self.get("manual_rb").set_active(False)
self.set_manual_network(True)
self.if_available_set(data, "net_address",
self.get("address").set_text)
self.if_available_set(data, "net_mask",
self.get("networkmask").set_text)
self.if_available_set(data, "net_gateway",
self.get("gateway").set_text)
def is_custom(self, data, key):
if data.has_key(key):
if data[key] != "":
return True
return False
def collect_data(self, data):
super(NetworkSettingsSection, self).collect_data(data)
data["net_mode"] = u"auto"
data["net_address"] = u""
data["net_mask"] = u""
data["net_gateway"] = u""
if self.get("manual_rb").get_active():
data["net_mode"] = u"manual"
if self.get("address").state == gtk.STATE_NORMAL:
data["net_address"] = self.get_text_of("address")
data["net_mask"] = self.get_text_of("networkmask")
if self.get("gateway").state == gtk.STATE_NORMAL:
data["net_gateway"] = self.get_text_of("gateway")
class NameServerSection(EditSection):
def __init__(self, parent):
super(NameServerSection, self).__init__(parent)
def set_custom_name(self, state):
self.get("ns_custom_text").set_sensitive(state)
def _on_type_changed(self, widget):
if widget is self.get("ns_custom_rb"):
self.set_custom_name(True)
else:
self.set_custom_name(False)
def listen_signals(self):
self.signal_connect("on_ns_default_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_custom_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_auto_rb_clicked",
self._on_type_changed)
def show_ui(self, data):
if data.has_key("name_mode"):
self.listen_signals()
if data["name_mode"] == "default":
self.get("ns_default_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "auto":
self.get("ns_auto_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "custom":
self.get("ns_custom_rb").set_active(True)
self.set_custom_name(True)
self.if_available_set(data, "name_server",
self.get("ns_custom_text").set_text)
def collect_data(self, data):
super(NameServerSection, self).collect_data(data)
data["name_mode"] = u"default"
data["name_server"] = u""
if self.get("ns_auto_rb").get_active():
data["name_mode"] = u"auto"
if self.get("ns_custom_rb").get_active():
data["name_mode"] = u"custom"
data["name_server"] = self.get_text_of("ns_custom_text")
class WirelessSection(EditSection):
def __init__(self, parent, password_state="hidden"):
super(WirelessSection, self).__init__(parent)
self.password_state = password_state
self.iface = parent.iface
self.package = parent._package
self.connection = parent._connection
# --- Password related
def show_password(self, state):
if (state == False) | (state == "hidden"):
self.get("hidepass_cb").hide()
self.get("pass_text").hide()
self.get("pass_lb").hide()
elif state == True:
self.get("hidepass_cb").show()
self.get("pass_text").show()
self.get("pass_lb").show()
if state == "hidden":
self.get("changepass_btn").show()
else:
self.get("changepass_btn").hide()
def change_password(self, widget=None):
self.show_password(True)
print "heyya"
authType = self.iface.authType(self.package,
self.connection)
authInfo = self.iface.authInfo(self.package,
self.connection)
authParams = self.iface.authParameters(self.package,
authType)
if len(authParams) == 1:
password = authInfo.values()[0]
self.get("pass_text").set_text(password)
self.get("hidepass_cb").set_active(True)
elif len(authParams) > 1:
print "\nTODO:learn what is securityDialog"
print "--> at svn-24515 / base.py line:474\n"
def hide_password(self, widget):
visibility = not widget.get_active()
self.get("pass_text").set_visibility(visibility)
# end Password related
def scan(self, widget=None):
self.get("scan_btn").hide()
self.wifiitems.set_scanning(True)
self.iface.scanRemote(self.device , self.package, self.wifilist)
+ def security_types_changed(self, widget):
+ index = widget.get_active()
+ if index == 0:
+ self.show_password(False)
+ else:
+ self.show_password(True)
def listen_signals(self):
+ self.signal_connect("on_security_types_changed",
+ self.security_types_changed)
#Password related
self.signal_connect("on_changepass_btn_clicked",
self.change_password)
self.signal_connect("on_hidepass_cb_toggled",
self.hide_password)
def set_security_types_style(self):
##Security Type ComboBox
model = gtk.ListStore(str)
security_types = self.get("security_types")
security_types.set_model(model)
cell = gtk.CellRendererText()
security_types.pack_start(cell)
security_types.add_attribute(cell,'text',0)
def prepare_security_types(self, authType):
self.set_security_types_style()
noauth = _("No Authentication")
self._authMethods = [("none", noauth)]
append_to_types = self.get("security_types").append_text
append_to_types(noauth)
self.get("security_types").set_active(0)
index = 1
self.with_password = False
for name, desc in self.iface.authMethods(self.package):
append_to_types(desc)
self._authMethods.append((name, desc))
if name == authType:
self.get("security_types").set_active(index)
self.with_password = True
index += 1
def on_wifi_clicked(self, widget, callback_data):
- print "clicked:", callback_data["get_connection"]()
+ data = callback_data["get_connection"]()
+ # data["remote"] = isim, data["encryption"]
+ print data
def wifilist(self, package, exception, args):
self.get("scan_btn").show()
self.signal_connect("on_scan_btn_clicked",
self.scan)
if not exception:
self.wifiitems.getConnections(args[0])
self.wifiitems.listen_change(self.on_wifi_clicked)
else:
print exception
def show_ui(self, data, caps):
self.listen_signals()
self.device = data["device_id"]
self.if_available_set(data, "remote",
self.get("essid_text").set_text)
modes = caps["modes"].split(",")
if "auth" in modes:
authType = self.iface.authType(self.parent._package,
self.parent._connection)
self.prepare_security_types(authType)
+ self.get("hidepass_cb").set_active(True)
if self.with_password:
self.show_password(self.password_state)
- if self.get("security_types").get_active() == 0:#No Auth
- self.show_password(False)
+ #if self.get("security_types").get_active() == 0:#No Auth
+ # self.show_password(False)
self.wifiitems = WifiItemHolder()
self.get("wireless_table").attach(self.wifiitems,
0, 1, 0, 4,
gtk.EXPAND|gtk.FILL,
gtk.EXPAND|gtk.FILL)
self.scan()
def collect_data(self, data):
super(WirelessSection, self).collect_data(data)
data["remote"] = self.get_text_of("essid_text")
data["apmac"] = u"" #??? what is it
#Security
data["auth"] = unicode(self._authMethods[
self.get("security_types").get_active()][0])
if data["auth"] != u"none":
params = self.iface.authParameters("wireless_tools",
data["auth"])
if len(params) == 1:
key = "auth_%s" % params[0][0]
if self.get("pass_text").props.visible:
data[key] = self.get_text_of("pass_text")
else:
info = self.iface.authInfo(self.parent._package,
self.parent._connection)
data[key] = info.values()[0]
else:
print "TODO:more than one security params"
print "at collect_data\n"
# end Edit Window Sections
class EditInterface(object):
"""Imports edit window glade
"""
def __init__(self, package, connection):
"""init
Arguments:
- `package`:
- `connection`:
"""
bind_glade_domain()
self.iface = NetworkIface()
self._package = package
self._connection = connection
self._xml = glade.XML("ui/edit.glade")
self.get = self._xml.get_widget
self.listen_signals()
self.insertData()
def apply(self, widget):
data = self.collect_data()
print data
try:
pass
self.iface.updateConnection(self._package,
data["name"],
data)
except Exception, e:
print "Exception:", unicode(e)
if not self.name == data["name"]:
self.iface.deleteConnection(self._package, self.name)
if self.is_up:
self.iface.connect(self._package, self.name)
self.getWindow().destroy()
def cancel(self, widget):
self.getWindow().destroy()
def listen_signals(self):
self._xml.signal_connect("apply_btn_clicked",
self.apply)
self._xml.signal_connect("cancel_btn_clicked",
self.cancel)
def insertData(self):
"""show preferences
"""
data = self.iface.info(self._package,
self._connection)
self.name = data["name"]
self.is_up = False
if data.has_key("state"):
if data["state"][0:2] == "up":
self.is_up = True
#Profile Frame
self.profile_frame = ProfileSection(self)
self.profile_frame.show_ui(data)
#Network Settings Frame
self.network_frame = NetworkSettingsSection(self)
self.network_frame.show_ui(data)
#Name Servers Frame
self.name_frame = NameServerSection(self)
self.name_frame.show_ui(data)
# Wireless Frame
if self._package == "wireless_tools":
caps = self.iface.capabilities(self._package)
self.wireless_frame = WirelessSection(self)
self.wireless_frame.show_ui(data, caps)
else:
self.get("wireless_frame").hide()
def collect_data(self):
data = {}
self.profile_frame.collect_data(data)
self.network_frame.collect_data(data)
self.name_frame.collect_data(data)
if self._package == "wireless_tools":
self.wireless_frame.collect_data(data)
return data
def getWindow(self):
"""returns window
"""
return self.get("window_edit")
diff --git a/ui/edit.glade b/ui/edit.glade
index 0f24060..8169888 100644
--- a/ui/edit.glade
+++ b/ui/edit.glade
@@ -1,589 +1,590 @@
<?xml version="1.0"?>
<glade-interface>
<!-- interface-requires gtk+ 2.16 -->
<!-- interface-naming-policy project-wide -->
<widget class="GtkWindow" id="window_edit">
<property name="title" translatable="yes" comments="Edit Cable Settings Window Title">Edit Connection</property>
<property name="default_width">640</property>
<child>
<widget class="GtkVBox" id="vbox1">
<property name="visible">True</property>
<property name="orientation">vertical</property>
<property name="spacing">6</property>
<child>
<widget class="GtkFrame" id="profile_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment1">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkHBox" id="hbox1">
<property name="visible">True</property>
<property name="spacing">2</property>
<child>
<widget class="GtkLabel" id="label3">
<property name="visible">True</property>
<property name="label" translatable="yes">Profile Name:</property>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="profilename">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="device_name_label">
<property name="visible">True</property>
<property name="xalign">0</property>
<property name="label">device name goes here </property>
<property name="use_markup">True</property>
<property name="ellipsize">middle</property>
</widget>
<packing>
<property name="pack_type">end</property>
<property name="position">2</property>
</packing>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label1">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Profile</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkFrame" id="wireless_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment4">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkTable" id="wireless_table">
<property name="visible">True</property>
<property name="n_rows">5</property>
<property name="n_columns">3</property>
<child>
<widget class="GtkButton" id="scan_btn">
<property name="label" translatable="yes">Scan</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<signal name="clicked" handler="on_scan_btn_clicked"/>
</widget>
<packing>
<property name="top_attach">4</property>
<property name="bottom_attach">5</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="label9">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Security Type:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="pass_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Password:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options">GTK_FILL</property>
</packing>
</child>
<child>
<widget class="GtkComboBox" id="security_types">
<property name="visible">True</property>
+ <signal name="changed" handler="on_security_types_changed"/>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="pass_text">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
<property name="invisible_char_set">True</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkCheckButton" id="hidepass_cb">
<property name="label" translatable="yes">Hide Password</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="draw_indicator">True</property>
<signal name="toggled" handler="on_hidepass_cb_toggled"/>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">3</property>
<property name="top_attach">3</property>
<property name="bottom_attach">4</property>
<property name="x_options"></property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="label5">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">ESSID:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="essid_text">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkButton" id="changepass_btn">
<property name="label" translatable="yes">Change Password</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<signal name="clicked" handler="on_changepass_btn_clicked"/>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">3</property>
<property name="top_attach">4</property>
<property name="bottom_attach">5</property>
<property name="x_options"></property>
<property name="y_options"></property>
</packing>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label8">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Wireless</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkFrame" id="network_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment2">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkVBox" id="vbox2">
<property name="visible">True</property>
<property name="orientation">vertical</property>
<property name="spacing">5</property>
<child>
<widget class="GtkRadioButton" id="dhcp_rb">
<property name="label" translatable="yes">Use DHCP</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<signal name="clicked" handler="on_dhcp_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkTable" id="table2">
<property name="visible">True</property>
<property name="n_rows">3</property>
<property name="n_columns">4</property>
<property name="row_spacing">5</property>
<child>
<widget class="GtkRadioButton" id="manual_rb">
<property name="label" translatable="yes">Use Manual Settings</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<property name="group">dhcp_rb</property>
<signal name="clicked" handler="on_manual_rb_clicked"/>
</widget>
</child>
<child>
<widget class="GtkLabel" id="address_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Address:</property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="networkmask_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Network Mask:</property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="gateway_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Default Gateway:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
<property name="y_options">GTK_EXPAND</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="address">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="networkmask">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="gateway">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
</packing>
</child>
<child>
<widget class="GtkCheckButton" id="custom_address">
<property name="label" translatable="yes">Custom</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="draw_indicator">True</property>
<signal name="toggled" handler="on_custom_address_toggled"/>
</widget>
<packing>
<property name="left_attach">3</property>
<property name="right_attach">4</property>
</packing>
</child>
<child>
<widget class="GtkCheckButton" id="custom_gateway">
<property name="label" translatable="yes">Custom</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="draw_indicator">True</property>
<signal name="toggled" handler="on_custom_gateway_toggled"/>
</widget>
<packing>
<property name="left_attach">3</property>
<property name="right_attach">4</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
</packing>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">1</property>
</packing>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label2">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Network Settings</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">2</property>
</packing>
</child>
<child>
<widget class="GtkFrame" id="ns_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment3">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkHBox" id="hbox2">
<property name="visible">True</property>
<property name="spacing">5</property>
<child>
<widget class="GtkRadioButton" id="ns_default_rb">
<property name="label" translatable="yes">Default</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<signal name="clicked" handler="on_ns_default_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkRadioButton" id="ns_auto_rb">
<property name="label" translatable="yes">Automatic</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<property name="group">ns_default_rb</property>
<signal name="clicked" handler="on_ns_auto_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkRadioButton" id="ns_custom_rb">
<property name="label" translatable="yes">Custom</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="draw_indicator">True</property>
<property name="group">ns_default_rb</property>
<signal name="clicked" handler="on_ns_custom_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">2</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="ns_custom_text">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="editable">False</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="position">3</property>
</packing>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label4">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Name Servers</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">3</property>
</packing>
</child>
<child>
<widget class="GtkHBox" id="hbox3">
<property name="visible">True</property>
<property name="spacing">5</property>
<child>
<widget class="GtkButton" id="cancel_btn">
<property name="label" translatable="yes">Cancel</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="use_underline">True</property>
<signal name="clicked" handler="cancel_btn_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="pack_type">end</property>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkButton" id="apply_btn">
<property name="label" translatable="yes">Apply</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="use_underline">True</property>
<signal name="clicked" handler="apply_btn_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="pack_type">end</property>
<property name="position">0</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="pack_type">end</property>
<property name="position">4</property>
</packing>
</child>
</widget>
</child>
</widget>
</glade-interface>
|
rdno/pardus-network-manager-gtk
|
70e8387b10d02f47adaa079e4c2b93bdcd4659c3
|
listen comar connection changes
|
diff --git a/network-manager-gtk.py b/network-manager-gtk.py
index 6f7ad07..fd41d18 100755
--- a/network-manager-gtk.py
+++ b/network-manager-gtk.py
@@ -1,106 +1,114 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import os
import pygtk
pygtk.require('2.0')
import gtk
import gobject
from network_manager_gtk.backend import NetworkIface
from network_manager_gtk.widgets import ConnectionWidget
from network_manager_gtk.widgets import MainInterface
from network_manager_gtk.widgets import EditInterface
class Base(object):
def __init__(self):
self._dbusMainLoop()
self.iface = NetworkIface()
#ui
self.main = MainInterface()
self.window = self.main.getWindow()
# show connection as Widgets
self.widgets = {}
self.showConnections()
self.holder = self.main.getHolder()
self.holder.add_with_viewport(self.vbox)
# listen for changes
self.iface.listen(self._listener)
def _onConnectionClicked(self, widget, callback_data):
self.iface.toggle(callback_data['package'],
callback_data['connection'])
def _onConnectionEdit(self, widget, callback_data):
a = EditInterface(callback_data['package'],
callback_data['connection'])
a.getWindow().show()
def _onConnectionDelete(self, widget, callback_data):
print "TODO:onConnection Delete"
def showConnections(self):
"""show connection on gui
"""
self.vbox = gtk.VBox(homogeneous=False, spacing=10)
for package in self.iface.packages():
self.widgets[package] = {}
for connection in self.iface.connections(package):
- state = self.iface.info(package, connection)[u"state"]
- con_wg = ConnectionWidget(package,
- connection,
- state)
- con_wg.connectSignals(self._onConnectionClicked,
- self._onConnectionEdit,
- self._onConnectionDelete)
- self.vbox.pack_start(con_wg, expand=False, fill=False)
- self.widgets[package][connection] = con_wg
-
+ self.add_to_vbox(package, connection)
+ def add_to_vbox(self, package, connection):
+ state = self.iface.info(package, connection)[u"state"]
+ con_wg = ConnectionWidget(package,
+ connection,
+ state)
+ con_wg.connectSignals(self._onConnectionClicked,
+ self._onConnectionEdit,
+ self._onConnectionDelete)
+ self.vbox.pack_start(con_wg, expand=False, fill=False)
+ self.widgets[package][connection] = con_wg
def _listener(self, package, signal, args):
"""comar listener
Arguments:
- `package`: package of item
- `signal`: comar signal type
- `args`: arguments
"""
args = map(lambda x: unicode(x), list(args))
if signal == "stateChanged":
self.widgets[package][args[0]].setMode(args[1:])
elif signal == "deviceChanged":
print "TODO:Listen comar signal deviceChanged "
elif signal == "connectionChanged":
- print "TODO:Listen comar signal connectionChanged"
+ if args[0] == u"changed":
+ pass#Nothing to do ?
+ elif args[0] == u"added":
+ self.add_to_vbox(package, args[1])
+ self.vbox.show_all()
+ elif args[0] == u"deleted":
+ self.vbox.remove(self.widgets[package][args[1]])
+ pass
def _dbusMainLoop(self):
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default = True)
def run(self, argv=None):
"""Runs the program
Arguments:
- `argv`: sys.argv
"""
self.window.show_all()
gtk.main()
if __name__ == "__main__":
import sys
app = Base()
app.run(sys.argv)
|
rdno/pardus-network-manager-gtk
|
70513c24556e000420e060a9ee99e0f5499be5c2
|
partly wireless editing support
|
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index 1685f6a..65d891c 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,523 +1,550 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
"""A special widget contains connection related stuff
"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
self._createUI()
def _createUI(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.setMode(self._state.split(' '))
def setMode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- `args`: state, detail
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
self._info.set_markup('<span color="green">'+
args[1]+
'</span>')
def connectSignals(self, click_signal, edit_signal, delete_signal):
"""connect widgets signals
Arguments:
- `click_signal`: toggle connection signal
- `edit_signal`: edit signal
- `delete_signal`: delete signal
"""
self.check_btn.connect("pressed", click_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.edit_btn.connect("clicked", edit_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.delete_btn.connect("clicked", delete_signal,
{"package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
class WifiItemHolder(gtk.ScrolledWindow):
"""holder for wifi connections
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
else:
data = None
return data
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
class MainInterface(object):
"""Imports main window glade
"""
def __init__(self):
"""import glade
"""
bind_glade_domain()
self._xml = glade.XML("ui/main.glade")
self._xml.signal_connect("on_window_main_destroy",
gtk.main_quit)
self._window = self._xml.get_widget("window_main")
self._holder = self._xml.get_widget("holder")
def getWindow(self):
"""returns window
"""
return self._window
def getHolder(self):
"""returns holder
"""
return self._holder
# --- Edit Window Sections (in ui: frame)
class EditSection(object):
def __init__(self, parent):
super(EditSection, self).__init__()
self.get = parent.get
self.signal_connect = parent._xml.signal_connect
self.parent = parent
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
def get_text_of(self, name):
"""gets text from widget in unicode"""
return unicode(self.get(name).get_text())
def collect_data(self, data):
"""collect data from ui and append datas to
given(data) dictionary"""
pass
class ProfileSection(EditSection):
def __init__(self, parent):
super(ProfileSection, self).__init__(parent)
def show_ui(self, data):
self.get("profilename").set_text(data[u"name"])
self.if_available_set(data, "device_name",
self.get("device_name_label").set_text)
self.device_id = data["device_id"]
#TODO:more than one device support
def collect_data(self, data):
super(ProfileSection, self).collect_data(data)
data["name"] = self.get_text_of("profilename")
data["device_id"] = unicode(self.device_id)
class NetworkSettingsSection(EditSection):
def __init__(self, parent):
super(NetworkSettingsSection, self).__init__(parent)
def _on_type_changed(self, widget):
if widget is self.get("dhcp_rb"):
self.set_manual_network(False)
else:
self.set_manual_network(True)
def set_manual_network(self, state):
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
# custom things
self.get("custom_gateway").set_sensitive(not state)
self.get("custom_address").set_sensitive(not state)
if not state:
self._on_custom_address(self.get("custom_address"))
self._on_custom_gateway(self.get("custom_gateway"))
def _on_custom_address(self, widget):
state = widget.get_active()
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
def _on_custom_gateway(self, widget):
state = widget.get_active()
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
def listen_signals(self):
self.signal_connect("on_dhcp_rb_clicked",
self._on_type_changed)
self.signal_connect("on_manual_rb_clicked",
self._on_type_changed)
self.signal_connect("on_custom_gateway_toggled",
self._on_custom_gateway)
self.signal_connect("on_custom_address_toggled",
self._on_custom_address)
def show_ui(self, data):
if data.has_key("net_mode"):
self.listen_signals()
if data["net_mode"] == "auto":
self.get("dhcp_rb").set_active(True)
self.set_manual_network(False)
if self.is_custom(data, "net_gateway"):
self.get("custom_gateway").set_active(True)
if self.is_custom(data, "net_address"):
self.get("custom_address").set_active(True)
else:
self.get("manual_rb").set_active(False)
self.set_manual_network(True)
self.if_available_set(data, "net_address",
self.get("address").set_text)
self.if_available_set(data, "net_mask",
self.get("networkmask").set_text)
self.if_available_set(data, "net_gateway",
self.get("gateway").set_text)
def is_custom(self, data, key):
if data.has_key(key):
if data[key] != "":
return True
return False
def collect_data(self, data):
super(NetworkSettingsSection, self).collect_data(data)
data["net_mode"] = u"auto"
data["net_address"] = u""
data["net_mask"] = u""
data["net_gateway"] = u""
if self.get("manual_rb").get_active():
data["net_mode"] = u"manual"
if self.get("address").state == gtk.STATE_NORMAL:
data["net_address"] = self.get_text_of("address")
data["net_mask"] = self.get_text_of("networkmask")
if self.get("gateway").state == gtk.STATE_NORMAL:
data["net_gateway"] = self.get_text_of("gateway")
class NameServerSection(EditSection):
def __init__(self, parent):
super(NameServerSection, self).__init__(parent)
def set_custom_name(self, state):
self.get("ns_custom_text").set_sensitive(state)
def _on_type_changed(self, widget):
if widget is self.get("ns_custom_rb"):
self.set_custom_name(True)
else:
self.set_custom_name(False)
def listen_signals(self):
self.signal_connect("on_ns_default_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_custom_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_auto_rb_clicked",
self._on_type_changed)
def show_ui(self, data):
if data.has_key("name_mode"):
self.listen_signals()
if data["name_mode"] == "default":
self.get("ns_default_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "auto":
self.get("ns_auto_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "custom":
self.get("ns_custom_rb").set_active(True)
self.set_custom_name(True)
self.if_available_set(data, "name_server",
self.get("ns_custom_text").set_text)
def collect_data(self, data):
super(NameServerSection, self).collect_data(data)
data["name_mode"] = u"default"
data["name_server"] = u""
if self.get("ns_auto_rb").get_active():
data["name_mode"] = u"auto"
if self.get("ns_custom_rb").get_active():
data["name_mode"] = u"custom"
data["name_server"] = self.get_text_of("ns_custom_text")
class WirelessSection(EditSection):
def __init__(self, parent, password_state="hidden"):
super(WirelessSection, self).__init__(parent)
self.password_state = password_state
self.iface = parent.iface
self.package = parent._package
self.connection = parent._connection
# --- Password related
def show_password(self, state):
if (state == False) | (state == "hidden"):
self.get("hidepass_cb").hide()
self.get("pass_text").hide()
self.get("pass_lb").hide()
elif state == True:
self.get("hidepass_cb").show()
self.get("pass_text").show()
self.get("pass_lb").show()
if state == "hidden":
self.get("changepass_btn").show()
else:
self.get("changepass_btn").hide()
def change_password(self, widget=None):
self.show_password(True)
+ print "heyya"
authType = self.iface.authType(self.package,
self.connection)
authInfo = self.iface.authInfo(self.package,
self.connection)
authParams = self.iface.authParameters(self.package,
authType)
if len(authParams) == 1:
password = authInfo.values()[0]
self.get("pass_text").set_text(password)
self.get("hidepass_cb").set_active(True)
elif len(authParams) > 1:
print "\nTODO:learn what is securityDialog"
print "--> at svn-24515 / base.py line:474\n"
def hide_password(self, widget):
visibility = not widget.get_active()
self.get("pass_text").set_visibility(visibility)
# end Password related
def scan(self, widget=None):
self.get("scan_btn").hide()
self.wifiitems.set_scanning(True)
self.iface.scanRemote(self.device , self.package, self.wifilist)
def listen_signals(self):
#Password related
self.signal_connect("on_changepass_btn_clicked",
self.change_password)
self.signal_connect("on_hidepass_cb_toggled",
self.hide_password)
def set_security_types_style(self):
##Security Type ComboBox
model = gtk.ListStore(str)
security_types = self.get("security_types")
security_types.set_model(model)
cell = gtk.CellRendererText()
security_types.pack_start(cell)
security_types.add_attribute(cell,'text',0)
def prepare_security_types(self, authType):
self.set_security_types_style()
noauth = _("No Authentication")
- self._authMethods = [(0, "none", noauth)]
+ self._authMethods = [("none", noauth)]
append_to_types = self.get("security_types").append_text
append_to_types(noauth)
self.get("security_types").set_active(0)
index = 1
self.with_password = False
for name, desc in self.iface.authMethods(self.package):
append_to_types(desc)
- self._authMethods.append((index, name, desc))
+ self._authMethods.append((name, desc))
if name == authType:
self.get("security_types").set_active(index)
self.with_password = True
index += 1
def on_wifi_clicked(self, widget, callback_data):
print "clicked:", callback_data["get_connection"]()
def wifilist(self, package, exception, args):
self.get("scan_btn").show()
self.signal_connect("on_scan_btn_clicked",
self.scan)
if not exception:
self.wifiitems.getConnections(args[0])
self.wifiitems.listen_change(self.on_wifi_clicked)
else:
print exception
def show_ui(self, data, caps):
+ self.listen_signals()
self.device = data["device_id"]
self.if_available_set(data, "remote",
self.get("essid_text").set_text)
modes = caps["modes"].split(",")
if "auth" in modes:
authType = self.iface.authType(self.parent._package,
self.parent._connection)
self.prepare_security_types(authType)
if self.with_password:
self.show_password(self.password_state)
if self.get("security_types").get_active() == 0:#No Auth
self.show_password(False)
self.wifiitems = WifiItemHolder()
self.get("wireless_table").attach(self.wifiitems,
0, 1, 0, 4,
gtk.EXPAND|gtk.FILL,
gtk.EXPAND|gtk.FILL)
self.scan()
+ def collect_data(self, data):
+ super(WirelessSection, self).collect_data(data)
+ data["remote"] = self.get_text_of("essid_text")
+ data["apmac"] = u"" #??? what is it
+
+ #Security
+ data["auth"] = unicode(self._authMethods[
+ self.get("security_types").get_active()][0])
+ if data["auth"] != u"none":
+ params = self.iface.authParameters("wireless_tools",
+ data["auth"])
+ if len(params) == 1:
+ key = "auth_%s" % params[0][0]
+ if self.get("pass_text").props.visible:
+ data[key] = self.get_text_of("pass_text")
+ else:
+ info = self.iface.authInfo(self.parent._package,
+ self.parent._connection)
+ data[key] = info.values()[0]
+ else:
+ print "TODO:more than one security params"
+ print "at collect_data\n"
+
# end Edit Window Sections
class EditInterface(object):
"""Imports edit window glade
"""
def __init__(self, package, connection):
"""init
Arguments:
- `package`:
- `connection`:
"""
bind_glade_domain()
self.iface = NetworkIface()
self._package = package
self._connection = connection
self._xml = glade.XML("ui/edit.glade")
self.get = self._xml.get_widget
self.listen_signals()
self.insertData()
def apply(self, widget):
data = self.collect_data()
+ print data
try:
- #to connect
+ pass
self.iface.updateConnection(self._package,
data["name"],
data)
except Exception, e:
print "Exception:", unicode(e)
if not self.name == data["name"]:
self.iface.deleteConnection(self._package, self.name)
if self.is_up:
self.iface.connect(self._package, self.name)
self.getWindow().destroy()
def cancel(self, widget):
self.getWindow().destroy()
def listen_signals(self):
self._xml.signal_connect("apply_btn_clicked",
self.apply)
self._xml.signal_connect("cancel_btn_clicked",
self.cancel)
def insertData(self):
"""show preferences
"""
data = self.iface.info(self._package,
self._connection)
self.name = data["name"]
self.is_up = False
if data.has_key("state"):
if data["state"][0:2] == "up":
self.is_up = True
#Profile Frame
self.profile_frame = ProfileSection(self)
self.profile_frame.show_ui(data)
#Network Settings Frame
self.network_frame = NetworkSettingsSection(self)
self.network_frame.show_ui(data)
#Name Servers Frame
self.name_frame = NameServerSection(self)
self.name_frame.show_ui(data)
# Wireless Frame
if self._package == "wireless_tools":
caps = self.iface.capabilities(self._package)
self.wireless_frame = WirelessSection(self)
self.wireless_frame.show_ui(data, caps)
else:
self.get("wireless_frame").hide()
- self.collect_data()
def collect_data(self):
data = {}
self.profile_frame.collect_data(data)
self.network_frame.collect_data(data)
self.name_frame.collect_data(data)
+ if self._package == "wireless_tools":
+ self.wireless_frame.collect_data(data)
return data
def getWindow(self):
"""returns window
"""
return self.get("window_edit")
|
rdno/pardus-network-manager-gtk
|
66494d52b4b214cc25d9c42f65388bbf9243c09a
|
connections are editable now
|
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index 1256262..1685f6a 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,455 +1,523 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
"""A special widget contains connection related stuff
"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
self._createUI()
def _createUI(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.setMode(self._state.split(' '))
def setMode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- `args`: state, detail
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
self._info.set_markup('<span color="green">'+
args[1]+
'</span>')
def connectSignals(self, click_signal, edit_signal, delete_signal):
"""connect widgets signals
Arguments:
- `click_signal`: toggle connection signal
- `edit_signal`: edit signal
- `delete_signal`: delete signal
"""
self.check_btn.connect("pressed", click_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.edit_btn.connect("clicked", edit_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.delete_btn.connect("clicked", delete_signal,
{"package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
class WifiItemHolder(gtk.ScrolledWindow):
"""holder for wifi connections
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
else:
data = None
return data
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
class MainInterface(object):
"""Imports main window glade
"""
def __init__(self):
"""import glade
"""
bind_glade_domain()
self._xml = glade.XML("ui/main.glade")
self._xml.signal_connect("on_window_main_destroy",
gtk.main_quit)
self._window = self._xml.get_widget("window_main")
self._holder = self._xml.get_widget("holder")
def getWindow(self):
"""returns window
"""
return self._window
def getHolder(self):
"""returns holder
"""
return self._holder
# --- Edit Window Sections (in ui: frame)
class EditSection(object):
def __init__(self, parent):
super(EditSection, self).__init__()
self.get = parent.get
self.signal_connect = parent._xml.signal_connect
self.parent = parent
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
+ def get_text_of(self, name):
+ """gets text from widget in unicode"""
+ return unicode(self.get(name).get_text())
+ def collect_data(self, data):
+ """collect data from ui and append datas to
+ given(data) dictionary"""
+ pass
class ProfileSection(EditSection):
def __init__(self, parent):
super(ProfileSection, self).__init__(parent)
def show_ui(self, data):
self.get("profilename").set_text(data[u"name"])
self.if_available_set(data, "device_name",
self.get("device_name_label").set_text)
+ self.device_id = data["device_id"]
#TODO:more than one device support
+ def collect_data(self, data):
+ super(ProfileSection, self).collect_data(data)
+ data["name"] = self.get_text_of("profilename")
+ data["device_id"] = unicode(self.device_id)
+
class NetworkSettingsSection(EditSection):
def __init__(self, parent):
super(NetworkSettingsSection, self).__init__(parent)
def _on_type_changed(self, widget):
if widget is self.get("dhcp_rb"):
self.set_manual_network(False)
else:
self.set_manual_network(True)
def set_manual_network(self, state):
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
# custom things
self.get("custom_gateway").set_sensitive(not state)
self.get("custom_address").set_sensitive(not state)
if not state:
self._on_custom_address(self.get("custom_address"))
self._on_custom_gateway(self.get("custom_gateway"))
def _on_custom_address(self, widget):
state = widget.get_active()
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
def _on_custom_gateway(self, widget):
state = widget.get_active()
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
def listen_signals(self):
self.signal_connect("on_dhcp_rb_clicked",
self._on_type_changed)
self.signal_connect("on_manual_rb_clicked",
self._on_type_changed)
self.signal_connect("on_custom_gateway_toggled",
self._on_custom_gateway)
self.signal_connect("on_custom_address_toggled",
self._on_custom_address)
def show_ui(self, data):
if data.has_key("net_mode"):
self.listen_signals()
if data["net_mode"] == "auto":
self.get("dhcp_rb").set_active(True)
self.set_manual_network(False)
- print data
if self.is_custom(data, "net_gateway"):
self.get("custom_gateway").set_active(True)
if self.is_custom(data, "net_address"):
self.get("custom_address").set_active(True)
else:
self.get("manual_rb").set_active(False)
self.set_manual_network(True)
self.if_available_set(data, "net_address",
self.get("address").set_text)
self.if_available_set(data, "net_mask",
self.get("networkmask").set_text)
self.if_available_set(data, "net_gateway",
self.get("gateway").set_text)
def is_custom(self, data, key):
if data.has_key(key):
if data[key] != "":
return True
return False
+ def collect_data(self, data):
+ super(NetworkSettingsSection, self).collect_data(data)
+ data["net_mode"] = u"auto"
+ data["net_address"] = u""
+ data["net_mask"] = u""
+ data["net_gateway"] = u""
+ if self.get("manual_rb").get_active():
+ data["net_mode"] = u"manual"
+ if self.get("address").state == gtk.STATE_NORMAL:
+ data["net_address"] = self.get_text_of("address")
+ data["net_mask"] = self.get_text_of("networkmask")
+ if self.get("gateway").state == gtk.STATE_NORMAL:
+ data["net_gateway"] = self.get_text_of("gateway")
class NameServerSection(EditSection):
def __init__(self, parent):
super(NameServerSection, self).__init__(parent)
def set_custom_name(self, state):
self.get("ns_custom_text").set_sensitive(state)
def _on_type_changed(self, widget):
if widget is self.get("ns_custom_rb"):
self.set_custom_name(True)
else:
self.set_custom_name(False)
def listen_signals(self):
self.signal_connect("on_ns_default_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_custom_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_auto_rb_clicked",
self._on_type_changed)
def show_ui(self, data):
if data.has_key("name_mode"):
self.listen_signals()
if data["name_mode"] == "default":
self.get("ns_default_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "auto":
self.get("ns_auto_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "custom":
self.get("ns_custom_rb").set_active(True)
self.set_custom_name(True)
self.if_available_set(data, "name_server",
self.get("ns_custom_text").set_text)
+ def collect_data(self, data):
+ super(NameServerSection, self).collect_data(data)
+ data["name_mode"] = u"default"
+ data["name_server"] = u""
+ if self.get("ns_auto_rb").get_active():
+ data["name_mode"] = u"auto"
+ if self.get("ns_custom_rb").get_active():
+ data["name_mode"] = u"custom"
+ data["name_server"] = self.get_text_of("ns_custom_text")
class WirelessSection(EditSection):
def __init__(self, parent, password_state="hidden"):
super(WirelessSection, self).__init__(parent)
self.password_state = password_state
self.iface = parent.iface
self.package = parent._package
self.connection = parent._connection
# --- Password related
def show_password(self, state):
if (state == False) | (state == "hidden"):
self.get("hidepass_cb").hide()
self.get("pass_text").hide()
self.get("pass_lb").hide()
elif state == True:
self.get("hidepass_cb").show()
self.get("pass_text").show()
self.get("pass_lb").show()
if state == "hidden":
self.get("changepass_btn").show()
else:
self.get("changepass_btn").hide()
def change_password(self, widget=None):
self.show_password(True)
authType = self.iface.authType(self.package,
self.connection)
authInfo = self.iface.authInfo(self.package,
self.connection)
authParams = self.iface.authParameters(self.package,
authType)
if len(authParams) == 1:
password = authInfo.values()[0]
self.get("pass_text").set_text(password)
self.get("hidepass_cb").set_active(True)
elif len(authParams) > 1:
print "\nTODO:learn what is securityDialog"
print "--> at svn-24515 / base.py line:474\n"
def hide_password(self, widget):
visibility = not widget.get_active()
self.get("pass_text").set_visibility(visibility)
# end Password related
def scan(self, widget=None):
self.get("scan_btn").hide()
self.wifiitems.set_scanning(True)
self.iface.scanRemote(self.device , self.package, self.wifilist)
def listen_signals(self):
#Password related
self.signal_connect("on_changepass_btn_clicked",
self.change_password)
self.signal_connect("on_hidepass_cb_toggled",
self.hide_password)
def set_security_types_style(self):
##Security Type ComboBox
model = gtk.ListStore(str)
security_types = self.get("security_types")
security_types.set_model(model)
cell = gtk.CellRendererText()
security_types.pack_start(cell)
security_types.add_attribute(cell,'text',0)
def prepare_security_types(self, authType):
self.set_security_types_style()
noauth = _("No Authentication")
self._authMethods = [(0, "none", noauth)]
append_to_types = self.get("security_types").append_text
append_to_types(noauth)
self.get("security_types").set_active(0)
index = 1
self.with_password = False
for name, desc in self.iface.authMethods(self.package):
append_to_types(desc)
self._authMethods.append((index, name, desc))
if name == authType:
self.get("security_types").set_active(index)
self.with_password = True
index += 1
def on_wifi_clicked(self, widget, callback_data):
print "clicked:", callback_data["get_connection"]()
def wifilist(self, package, exception, args):
self.get("scan_btn").show()
self.signal_connect("on_scan_btn_clicked",
self.scan)
if not exception:
self.wifiitems.getConnections(args[0])
self.wifiitems.listen_change(self.on_wifi_clicked)
else:
print exception
def show_ui(self, data, caps):
self.device = data["device_id"]
self.if_available_set(data, "remote",
self.get("essid_text").set_text)
modes = caps["modes"].split(",")
if "auth" in modes:
authType = self.iface.authType(self.parent._package,
self.parent._connection)
self.prepare_security_types(authType)
if self.with_password:
self.show_password(self.password_state)
if self.get("security_types").get_active() == 0:#No Auth
self.show_password(False)
self.wifiitems = WifiItemHolder()
self.get("wireless_table").attach(self.wifiitems,
0, 1, 0, 4,
gtk.EXPAND|gtk.FILL,
gtk.EXPAND|gtk.FILL)
self.scan()
# end Edit Window Sections
class EditInterface(object):
"""Imports edit window glade
"""
def __init__(self, package, connection):
"""init
Arguments:
- `package`:
- `connection`:
"""
bind_glade_domain()
self.iface = NetworkIface()
self._package = package
self._connection = connection
self._xml = glade.XML("ui/edit.glade")
self.get = self._xml.get_widget
+ self.listen_signals()
self.insertData()
+ def apply(self, widget):
+ data = self.collect_data()
+ try:
+ #to connect
+ self.iface.updateConnection(self._package,
+ data["name"],
+ data)
+ except Exception, e:
+ print "Exception:", unicode(e)
+
+ if not self.name == data["name"]:
+ self.iface.deleteConnection(self._package, self.name)
+ if self.is_up:
+ self.iface.connect(self._package, self.name)
+ self.getWindow().destroy()
+ def cancel(self, widget):
+ self.getWindow().destroy()
+ def listen_signals(self):
+ self._xml.signal_connect("apply_btn_clicked",
+ self.apply)
+ self._xml.signal_connect("cancel_btn_clicked",
+ self.cancel)
def insertData(self):
"""show preferences
"""
data = self.iface.info(self._package,
self._connection)
+ self.name = data["name"]
+ self.is_up = False
+ if data.has_key("state"):
+ if data["state"][0:2] == "up":
+ self.is_up = True
#Profile Frame
- profile_frame = ProfileSection(self)
- profile_frame.show_ui(data)
+ self.profile_frame = ProfileSection(self)
+ self.profile_frame.show_ui(data)
#Network Settings Frame
- network_frame = NetworkSettingsSection(self)
- network_frame.show_ui(data)
+ self.network_frame = NetworkSettingsSection(self)
+ self.network_frame.show_ui(data)
#Name Servers Frame
- name_frame = NameServerSection(self)
- name_frame.show_ui(data)
+ self.name_frame = NameServerSection(self)
+ self.name_frame.show_ui(data)
# Wireless Frame
if self._package == "wireless_tools":
caps = self.iface.capabilities(self._package)
- wireless_frame = WirelessSection(self)
- wireless_frame.show_ui(data, caps)
+ self.wireless_frame = WirelessSection(self)
+ self.wireless_frame.show_ui(data, caps)
else:
self.get("wireless_frame").hide()
-
+ self.collect_data()
+ def collect_data(self):
+ data = {}
+ self.profile_frame.collect_data(data)
+ self.network_frame.collect_data(data)
+ self.name_frame.collect_data(data)
+ return data
def getWindow(self):
"""returns window
"""
return self.get("window_edit")
diff --git a/ui/edit.glade b/ui/edit.glade
index d76011b..0f24060 100644
--- a/ui/edit.glade
+++ b/ui/edit.glade
@@ -43,545 +43,547 @@
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="device_name_label">
<property name="visible">True</property>
<property name="xalign">0</property>
<property name="label">device name goes here </property>
<property name="use_markup">True</property>
<property name="ellipsize">middle</property>
</widget>
<packing>
<property name="pack_type">end</property>
<property name="position">2</property>
</packing>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label1">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Profile</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkFrame" id="wireless_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment4">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkTable" id="wireless_table">
<property name="visible">True</property>
<property name="n_rows">5</property>
<property name="n_columns">3</property>
<child>
<widget class="GtkButton" id="scan_btn">
<property name="label" translatable="yes">Scan</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<signal name="clicked" handler="on_scan_btn_clicked"/>
</widget>
<packing>
<property name="top_attach">4</property>
<property name="bottom_attach">5</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="label9">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Security Type:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="pass_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Password:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options">GTK_FILL</property>
</packing>
</child>
<child>
<widget class="GtkComboBox" id="security_types">
<property name="visible">True</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="pass_text">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
<property name="invisible_char_set">True</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkCheckButton" id="hidepass_cb">
<property name="label" translatable="yes">Hide Password</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="draw_indicator">True</property>
<signal name="toggled" handler="on_hidepass_cb_toggled"/>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">3</property>
<property name="top_attach">3</property>
<property name="bottom_attach">4</property>
<property name="x_options"></property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="label5">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">ESSID:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="essid_text">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkButton" id="changepass_btn">
<property name="label" translatable="yes">Change Password</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<signal name="clicked" handler="on_changepass_btn_clicked"/>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">3</property>
<property name="top_attach">4</property>
<property name="bottom_attach">5</property>
<property name="x_options"></property>
<property name="y_options"></property>
</packing>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label8">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Wireless</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkFrame" id="network_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment2">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkVBox" id="vbox2">
<property name="visible">True</property>
<property name="orientation">vertical</property>
<property name="spacing">5</property>
<child>
<widget class="GtkRadioButton" id="dhcp_rb">
<property name="label" translatable="yes">Use DHCP</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<signal name="clicked" handler="on_dhcp_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkTable" id="table2">
<property name="visible">True</property>
<property name="n_rows">3</property>
<property name="n_columns">4</property>
<property name="row_spacing">5</property>
<child>
<widget class="GtkRadioButton" id="manual_rb">
<property name="label" translatable="yes">Use Manual Settings</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<property name="group">dhcp_rb</property>
<signal name="clicked" handler="on_manual_rb_clicked"/>
</widget>
</child>
<child>
<widget class="GtkLabel" id="address_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Address:</property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="networkmask_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Network Mask:</property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="gateway_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Default Gateway:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
<property name="y_options">GTK_EXPAND</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="address">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="networkmask">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="gateway">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
</packing>
</child>
<child>
<widget class="GtkCheckButton" id="custom_address">
<property name="label" translatable="yes">Custom</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="draw_indicator">True</property>
<signal name="toggled" handler="on_custom_address_toggled"/>
</widget>
<packing>
<property name="left_attach">3</property>
<property name="right_attach">4</property>
</packing>
</child>
<child>
<widget class="GtkCheckButton" id="custom_gateway">
<property name="label" translatable="yes">Custom</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="draw_indicator">True</property>
<signal name="toggled" handler="on_custom_gateway_toggled"/>
</widget>
<packing>
<property name="left_attach">3</property>
<property name="right_attach">4</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
</packing>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">1</property>
</packing>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label2">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Network Settings</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">2</property>
</packing>
</child>
<child>
<widget class="GtkFrame" id="ns_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment3">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkHBox" id="hbox2">
<property name="visible">True</property>
<property name="spacing">5</property>
<child>
<widget class="GtkRadioButton" id="ns_default_rb">
<property name="label" translatable="yes">Default</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<signal name="clicked" handler="on_ns_default_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkRadioButton" id="ns_auto_rb">
<property name="label" translatable="yes">Automatic</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<property name="group">ns_default_rb</property>
<signal name="clicked" handler="on_ns_auto_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkRadioButton" id="ns_custom_rb">
<property name="label" translatable="yes">Custom</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="draw_indicator">True</property>
<property name="group">ns_default_rb</property>
<signal name="clicked" handler="on_ns_custom_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">2</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="ns_custom_text">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="editable">False</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="position">3</property>
</packing>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label4">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Name Servers</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">3</property>
</packing>
</child>
<child>
<widget class="GtkHBox" id="hbox3">
<property name="visible">True</property>
<property name="spacing">5</property>
<child>
<widget class="GtkButton" id="cancel_btn">
<property name="label" translatable="yes">Cancel</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="use_underline">True</property>
+ <signal name="clicked" handler="cancel_btn_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="pack_type">end</property>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkButton" id="apply_btn">
<property name="label" translatable="yes">Apply</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="use_underline">True</property>
+ <signal name="clicked" handler="apply_btn_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="pack_type">end</property>
<property name="position">0</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="pack_type">end</property>
<property name="position">4</property>
</packing>
</child>
</widget>
</child>
</widget>
</glade-interface>
|
rdno/pardus-network-manager-gtk
|
a995a79ea38edd1da3eb12aa46bbc4eeb54b6b9b
|
added custom_address and custom_gateway checkboxes
|
diff --git a/network_manager_gtk/widgets.py b/network_manager_gtk/widgets.py
index 38c0aca..1256262 100644
--- a/network_manager_gtk/widgets.py
+++ b/network_manager_gtk/widgets.py
@@ -1,425 +1,455 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Rıdvan Ãrsvuran (C) 2009
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from translation import _, bind_glade_domain
from backend import NetworkIface
import pygtk
pygtk.require('2.0')
import pango
import gtk
import gobject
from gtk import glade
class ConnectionWidget(gtk.Table):
"""A special widget contains connection related stuff
"""
def __init__(self, package_name, connection_name, state=None):
"""init
Arguments:
- `package_name`: package of this (like wireless_tools)
- `connection_name`: user's connection name
- `state`: connection state
"""
gtk.Table.__init__(self, rows=2, columns=4)
self._package_name = package_name
self._connection_name = connection_name
self._state = state
self._createUI()
def _createUI(self):
"""creates UI
"""
self.check_btn = gtk.CheckButton()
self._label = gtk.Label(self._connection_name)
self._info = gtk.Label(self._state)
self._label.set_alignment(0.0, 0.5)
self._info.set_alignment(0.0, 0.5)
self.edit_btn = gtk.Button(_('Edit'))
self.delete_btn = gtk.Button(_('Delete'))
self.attach(self.check_btn, 0, 1, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self._label, 1 , 2, 0, 1,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self._info, 1 , 2, 1, 2,
gtk.EXPAND|gtk.FILL, gtk.SHRINK)
self.attach(self.edit_btn, 2, 3, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.attach(self.delete_btn, 3, 4, 0, 2,
gtk.SHRINK, gtk.SHRINK)
self.setMode(self._state.split(' '))
def setMode(self, args):
"""sets _info label text
and is _on or not
Arguments:
- `args`: state, detail
"""
detail = ""
if len(args) > 1:
detail = args[1]
states = {"down" : _("Disconnected"),
"up" : _("Connected"),
"connecting" : _("Connecting"),
"inaccessible": detail,
"unplugged" : _("Cable or device is unplugged.")}
if args[0] != "up":
self.check_btn.set_active(False)
self._info.set_text(states[args[0]])
else:
self.check_btn.set_active(True)
self._info.set_markup('<span color="green">'+
args[1]+
'</span>')
def connectSignals(self, click_signal, edit_signal, delete_signal):
"""connect widgets signals
Arguments:
- `click_signal`: toggle connection signal
- `edit_signal`: edit signal
- `delete_signal`: delete signal
"""
self.check_btn.connect("pressed", click_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.edit_btn.connect("clicked", edit_signal,
{"package":self._package_name,
"connection":self._connection_name})
self.delete_btn.connect("clicked", delete_signal,
{"package":self._package_name,
"connection":self._connection_name})
gobject.type_register(ConnectionWidget)
class WifiItemHolder(gtk.ScrolledWindow):
"""holder for wifi connections
"""
def __init__(self):
"""init
"""
gtk.ScrolledWindow.__init__(self)
self.set_shadow_type(gtk.SHADOW_IN)
self.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
def setup_view(self):
self.store = gtk.ListStore(str, str)
column = lambda x, y:gtk.TreeViewColumn(x,
gtk.CellRendererText(),
text=y)
self.view = gtk.TreeView(self.store)
self.view.append_column(column(_("Name"), 0))
self.view.append_column(column(_("Quality"), 1))
def get_active(self):
cursor = self.view.get_cursor()
if cursor[0]:
data = self.data[cursor[0][0]]
else:
data = None
return data
def listen_change(self, handler):
self.view.connect("cursor-changed", handler,
{"get_connection":self.get_active})
def getConnections(self, data):
self.set_scanning(False)
self.items = []
self.data = []
self.setup_view()
for remote in data:
self.store.append([remote["remote"],
_("%d%%") % int(remote["quality"])])
self.data.append(remote)
self.add_with_viewport(self.view)
self.show_all()
def set_scanning(self, is_scanning):
if is_scanning:
if self.get_child():
self.remove(self.get_child())
self.scan_lb = gtk.Label(_("Scanning..."))
self.add_with_viewport(self.scan_lb)
self.show_all()
else:
self.remove(self.get_child())
gobject.type_register(WifiItemHolder)
class MainInterface(object):
"""Imports main window glade
"""
def __init__(self):
"""import glade
"""
bind_glade_domain()
self._xml = glade.XML("ui/main.glade")
self._xml.signal_connect("on_window_main_destroy",
gtk.main_quit)
self._window = self._xml.get_widget("window_main")
self._holder = self._xml.get_widget("holder")
def getWindow(self):
"""returns window
"""
return self._window
def getHolder(self):
"""returns holder
"""
return self._holder
# --- Edit Window Sections (in ui: frame)
class EditSection(object):
def __init__(self, parent):
super(EditSection, self).__init__()
self.get = parent.get
self.signal_connect = parent._xml.signal_connect
self.parent = parent
def if_available_set(self, data, key, method):
"""if DATA dictionary has KEY execute METHOD with
arg:data[key]"""
if data.has_key(key):
method(data[key])
class ProfileSection(EditSection):
def __init__(self, parent):
super(ProfileSection, self).__init__(parent)
def show_ui(self, data):
self.get("profilename").set_text(data[u"name"])
self.if_available_set(data, "device_name",
self.get("device_name_label").set_text)
#TODO:more than one device support
class NetworkSettingsSection(EditSection):
def __init__(self, parent):
super(NetworkSettingsSection, self).__init__(parent)
def _on_type_changed(self, widget):
if widget is self.get("dhcp_rb"):
self.set_manual_network(False)
else:
self.set_manual_network(True)
def set_manual_network(self, state):
self.get("address").set_sensitive(state)
self.get("address_lb").set_sensitive(state)
self.get("networkmask").set_sensitive(state)
self.get("networkmask_lb").set_sensitive(state)
self.get("gateway").set_sensitive(state)
self.get("gateway_lb").set_sensitive(state)
+ # custom things
+ self.get("custom_gateway").set_sensitive(not state)
+ self.get("custom_address").set_sensitive(not state)
+ if not state:
+ self._on_custom_address(self.get("custom_address"))
+ self._on_custom_gateway(self.get("custom_gateway"))
+ def _on_custom_address(self, widget):
+ state = widget.get_active()
+ self.get("address").set_sensitive(state)
+ self.get("address_lb").set_sensitive(state)
+ self.get("networkmask").set_sensitive(state)
+ self.get("networkmask_lb").set_sensitive(state)
+ def _on_custom_gateway(self, widget):
+ state = widget.get_active()
+ self.get("gateway").set_sensitive(state)
+ self.get("gateway_lb").set_sensitive(state)
def listen_signals(self):
self.signal_connect("on_dhcp_rb_clicked",
self._on_type_changed)
self.signal_connect("on_manual_rb_clicked",
self._on_type_changed)
+ self.signal_connect("on_custom_gateway_toggled",
+ self._on_custom_gateway)
+ self.signal_connect("on_custom_address_toggled",
+ self._on_custom_address)
def show_ui(self, data):
if data.has_key("net_mode"):
self.listen_signals()
if data["net_mode"] == "auto":
self.get("dhcp_rb").set_active(True)
self.set_manual_network(False)
+ print data
+ if self.is_custom(data, "net_gateway"):
+ self.get("custom_gateway").set_active(True)
+ if self.is_custom(data, "net_address"):
+ self.get("custom_address").set_active(True)
else:
self.get("manual_rb").set_active(False)
self.set_manual_network(True)
self.if_available_set(data, "net_address",
self.get("address").set_text)
self.if_available_set(data, "net_mask",
self.get("networkmask").set_text)
self.if_available_set(data, "net_gateway",
self.get("gateway").set_text)
+ def is_custom(self, data, key):
+ if data.has_key(key):
+ if data[key] != "":
+ return True
+ return False
class NameServerSection(EditSection):
def __init__(self, parent):
super(NameServerSection, self).__init__(parent)
def set_custom_name(self, state):
self.get("ns_custom_text").set_sensitive(state)
def _on_type_changed(self, widget):
if widget is self.get("ns_custom_rb"):
self.set_custom_name(True)
else:
self.set_custom_name(False)
def listen_signals(self):
self.signal_connect("on_ns_default_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_custom_rb_clicked",
self._on_type_changed)
self.signal_connect("on_ns_auto_rb_clicked",
self._on_type_changed)
def show_ui(self, data):
if data.has_key("name_mode"):
self.listen_signals()
if data["name_mode"] == "default":
self.get("ns_default_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "auto":
self.get("ns_auto_rb").set_active(True)
self.set_custom_name(False)
elif data["name_mode"] == "custom":
self.get("ns_custom_rb").set_active(True)
self.set_custom_name(True)
self.if_available_set(data, "name_server",
self.get("ns_custom_text").set_text)
class WirelessSection(EditSection):
def __init__(self, parent, password_state="hidden"):
super(WirelessSection, self).__init__(parent)
self.password_state = password_state
self.iface = parent.iface
self.package = parent._package
self.connection = parent._connection
# --- Password related
def show_password(self, state):
if (state == False) | (state == "hidden"):
self.get("hidepass_cb").hide()
self.get("pass_text").hide()
self.get("pass_lb").hide()
elif state == True:
self.get("hidepass_cb").show()
self.get("pass_text").show()
self.get("pass_lb").show()
if state == "hidden":
self.get("changepass_btn").show()
else:
self.get("changepass_btn").hide()
def change_password(self, widget=None):
self.show_password(True)
authType = self.iface.authType(self.package,
self.connection)
authInfo = self.iface.authInfo(self.package,
self.connection)
authParams = self.iface.authParameters(self.package,
authType)
if len(authParams) == 1:
password = authInfo.values()[0]
self.get("pass_text").set_text(password)
self.get("hidepass_cb").set_active(True)
elif len(authParams) > 1:
print "\nTODO:learn what is securityDialog"
print "--> at svn-24515 / base.py line:474\n"
def hide_password(self, widget):
visibility = not widget.get_active()
self.get("pass_text").set_visibility(visibility)
# end Password related
def scan(self, widget=None):
self.get("scan_btn").hide()
self.wifiitems.set_scanning(True)
self.iface.scanRemote(self.device , self.package, self.wifilist)
def listen_signals(self):
#Password related
self.signal_connect("on_changepass_btn_clicked",
self.change_password)
self.signal_connect("on_hidepass_cb_toggled",
self.hide_password)
def set_security_types_style(self):
##Security Type ComboBox
model = gtk.ListStore(str)
security_types = self.get("security_types")
security_types.set_model(model)
cell = gtk.CellRendererText()
security_types.pack_start(cell)
security_types.add_attribute(cell,'text',0)
def prepare_security_types(self, authType):
self.set_security_types_style()
noauth = _("No Authentication")
self._authMethods = [(0, "none", noauth)]
append_to_types = self.get("security_types").append_text
append_to_types(noauth)
self.get("security_types").set_active(0)
index = 1
self.with_password = False
for name, desc in self.iface.authMethods(self.package):
append_to_types(desc)
self._authMethods.append((index, name, desc))
if name == authType:
self.get("security_types").set_active(index)
self.with_password = True
index += 1
def on_wifi_clicked(self, widget, callback_data):
print "clicked:", callback_data["get_connection"]()
def wifilist(self, package, exception, args):
self.get("scan_btn").show()
self.signal_connect("on_scan_btn_clicked",
self.scan)
if not exception:
self.wifiitems.getConnections(args[0])
self.wifiitems.listen_change(self.on_wifi_clicked)
else:
print exception
def show_ui(self, data, caps):
self.device = data["device_id"]
self.if_available_set(data, "remote",
self.get("essid_text").set_text)
modes = caps["modes"].split(",")
if "auth" in modes:
authType = self.iface.authType(self.parent._package,
self.parent._connection)
self.prepare_security_types(authType)
if self.with_password:
self.show_password(self.password_state)
- if self.get("security_types").get_active() == 0:
+ if self.get("security_types").get_active() == 0:#No Auth
self.show_password(False)
self.wifiitems = WifiItemHolder()
self.get("wireless_table").attach(self.wifiitems,
0, 1, 0, 4,
gtk.EXPAND|gtk.FILL,
gtk.EXPAND|gtk.FILL)
self.scan()
# end Edit Window Sections
class EditInterface(object):
"""Imports edit window glade
"""
def __init__(self, package, connection):
"""init
Arguments:
- `package`:
- `connection`:
"""
bind_glade_domain()
self.iface = NetworkIface()
self._package = package
self._connection = connection
self._xml = glade.XML("ui/edit.glade")
self.get = self._xml.get_widget
self.insertData()
def insertData(self):
"""show preferences
"""
data = self.iface.info(self._package,
self._connection)
#Profile Frame
profile_frame = ProfileSection(self)
profile_frame.show_ui(data)
#Network Settings Frame
network_frame = NetworkSettingsSection(self)
network_frame.show_ui(data)
#Name Servers Frame
name_frame = NameServerSection(self)
name_frame.show_ui(data)
# Wireless Frame
if self._package == "wireless_tools":
caps = self.iface.capabilities(self._package)
wireless_frame = WirelessSection(self)
wireless_frame.show_ui(data, caps)
else:
self.get("wireless_frame").hide()
def getWindow(self):
"""returns window
"""
return self.get("window_edit")
diff --git a/ui/edit.glade b/ui/edit.glade
index 8dbcb15..d76011b 100644
--- a/ui/edit.glade
+++ b/ui/edit.glade
@@ -1,554 +1,587 @@
<?xml version="1.0"?>
<glade-interface>
<!-- interface-requires gtk+ 2.16 -->
<!-- interface-naming-policy project-wide -->
<widget class="GtkWindow" id="window_edit">
<property name="title" translatable="yes" comments="Edit Cable Settings Window Title">Edit Connection</property>
<property name="default_width">640</property>
<child>
<widget class="GtkVBox" id="vbox1">
<property name="visible">True</property>
<property name="orientation">vertical</property>
<property name="spacing">6</property>
<child>
<widget class="GtkFrame" id="profile_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment1">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkHBox" id="hbox1">
<property name="visible">True</property>
<property name="spacing">2</property>
<child>
<widget class="GtkLabel" id="label3">
<property name="visible">True</property>
<property name="label" translatable="yes">Profile Name:</property>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="profilename">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="device_name_label">
<property name="visible">True</property>
<property name="xalign">0</property>
<property name="label">device name goes here </property>
<property name="use_markup">True</property>
<property name="ellipsize">middle</property>
</widget>
<packing>
<property name="pack_type">end</property>
<property name="position">2</property>
</packing>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label1">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Profile</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkFrame" id="wireless_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment4">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkTable" id="wireless_table">
<property name="visible">True</property>
<property name="n_rows">5</property>
<property name="n_columns">3</property>
<child>
<widget class="GtkButton" id="scan_btn">
<property name="label" translatable="yes">Scan</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<signal name="clicked" handler="on_scan_btn_clicked"/>
</widget>
<packing>
<property name="top_attach">4</property>
<property name="bottom_attach">5</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="label9">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Security Type:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="pass_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Password:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options">GTK_FILL</property>
</packing>
</child>
<child>
<widget class="GtkComboBox" id="security_types">
<property name="visible">True</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="pass_text">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
<property name="invisible_char_set">True</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkCheckButton" id="hidepass_cb">
<property name="label" translatable="yes">Hide Password</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="draw_indicator">True</property>
<signal name="toggled" handler="on_hidepass_cb_toggled"/>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">3</property>
<property name="top_attach">3</property>
<property name="bottom_attach">4</property>
<property name="x_options"></property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="label5">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">ESSID:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="essid_text">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkButton" id="changepass_btn">
<property name="label" translatable="yes">Change Password</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<signal name="clicked" handler="on_changepass_btn_clicked"/>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">3</property>
<property name="top_attach">4</property>
<property name="bottom_attach">5</property>
<property name="x_options"></property>
<property name="y_options"></property>
</packing>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label8">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Wireless</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkFrame" id="network_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment2">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkVBox" id="vbox2">
<property name="visible">True</property>
<property name="orientation">vertical</property>
<property name="spacing">5</property>
<child>
<widget class="GtkRadioButton" id="dhcp_rb">
<property name="label" translatable="yes">Use DHCP</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<signal name="clicked" handler="on_dhcp_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkTable" id="table2">
<property name="visible">True</property>
<property name="n_rows">3</property>
- <property name="n_columns">3</property>
+ <property name="n_columns">4</property>
<property name="row_spacing">5</property>
<child>
<widget class="GtkRadioButton" id="manual_rb">
<property name="label" translatable="yes">Use Manual Settings</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<property name="group">dhcp_rb</property>
<signal name="clicked" handler="on_manual_rb_clicked"/>
</widget>
</child>
<child>
<widget class="GtkLabel" id="address_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Address:</property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="networkmask_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Network Mask:</property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
<property name="x_options">GTK_FILL</property>
<property name="y_options"></property>
</packing>
</child>
<child>
<widget class="GtkLabel" id="gateway_lb">
<property name="visible">True</property>
<property name="xalign">1</property>
<property name="label" translatable="yes">Default Gateway:</property>
</widget>
<packing>
<property name="left_attach">1</property>
<property name="right_attach">2</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
<property name="y_options">GTK_EXPAND</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="address">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="networkmask">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">1</property>
<property name="bottom_attach">2</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="gateway">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="left_attach">2</property>
<property name="right_attach">3</property>
<property name="top_attach">2</property>
<property name="bottom_attach">3</property>
</packing>
</child>
+ <child>
+ <widget class="GtkCheckButton" id="custom_address">
+ <property name="label" translatable="yes">Custom</property>
+ <property name="visible">True</property>
+ <property name="can_focus">True</property>
+ <property name="receives_default">False</property>
+ <property name="draw_indicator">True</property>
+ <signal name="toggled" handler="on_custom_address_toggled"/>
+ </widget>
+ <packing>
+ <property name="left_attach">3</property>
+ <property name="right_attach">4</property>
+ </packing>
+ </child>
+ <child>
+ <widget class="GtkCheckButton" id="custom_gateway">
+ <property name="label" translatable="yes">Custom</property>
+ <property name="visible">True</property>
+ <property name="can_focus">True</property>
+ <property name="receives_default">False</property>
+ <property name="draw_indicator">True</property>
+ <signal name="toggled" handler="on_custom_gateway_toggled"/>
+ </widget>
+ <packing>
+ <property name="left_attach">3</property>
+ <property name="right_attach">4</property>
+ <property name="top_attach">2</property>
+ <property name="bottom_attach">3</property>
+ </packing>
+ </child>
+ <child>
+ <placeholder/>
+ </child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">1</property>
</packing>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label2">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Network Settings</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">2</property>
</packing>
</child>
<child>
<widget class="GtkFrame" id="ns_frame">
<property name="visible">True</property>
<property name="label_xalign">0</property>
<property name="shadow_type">none</property>
<child>
<widget class="GtkAlignment" id="alignment3">
<property name="visible">True</property>
<property name="left_padding">12</property>
<child>
<widget class="GtkHBox" id="hbox2">
<property name="visible">True</property>
<property name="spacing">5</property>
<child>
<widget class="GtkRadioButton" id="ns_default_rb">
<property name="label" translatable="yes">Default</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<signal name="clicked" handler="on_ns_default_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkRadioButton" id="ns_auto_rb">
<property name="label" translatable="yes">Automatic</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="active">True</property>
<property name="draw_indicator">True</property>
<property name="group">ns_default_rb</property>
<signal name="clicked" handler="on_ns_auto_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkRadioButton" id="ns_custom_rb">
<property name="label" translatable="yes">Custom</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="draw_indicator">True</property>
<property name="group">ns_default_rb</property>
<signal name="clicked" handler="on_ns_custom_rb_clicked"/>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">2</property>
</packing>
</child>
<child>
<widget class="GtkEntry" id="ns_custom_text">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="editable">False</property>
<property name="invisible_char">●</property>
</widget>
<packing>
<property name="position">3</property>
</packing>
</child>
</widget>
</child>
</widget>
</child>
<child>
<widget class="GtkLabel" id="label4">
<property name="visible">True</property>
<property name="label" translatable="yes"><b>Name Servers</b></property>
<property name="use_markup">True</property>
</widget>
<packing>
<property name="type">label_item</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="position">3</property>
</packing>
</child>
<child>
<widget class="GtkHBox" id="hbox3">
<property name="visible">True</property>
<property name="spacing">5</property>
<child>
<widget class="GtkButton" id="cancel_btn">
<property name="label" translatable="yes">Cancel</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="use_underline">True</property>
</widget>
<packing>
<property name="expand">False</property>
<property name="pack_type">end</property>
<property name="position">1</property>
</packing>
</child>
<child>
<widget class="GtkButton" id="apply_btn">
<property name="label" translatable="yes">Apply</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="use_underline">True</property>
</widget>
<packing>
<property name="expand">False</property>
<property name="pack_type">end</property>
<property name="position">0</property>
</packing>
</child>
</widget>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="pack_type">end</property>
<property name="position">4</property>
</packing>
</child>
</widget>
</child>
</widget>
</glade-interface>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.