Felipe Borges: Help GNOME defend its trademark against Groupon
11 de Novembro de 2014, 13:34 - sem comentários aindaRecently Groupon announced a new tablet-based platform named “GNOME”. If you’re reading this, you probably already know that GNOME has been a big and popular free software project for the past 17 years, *and a registered trademark since 2006*.
It’s outrageous that a billion dollars company such as Groupon would not have heard of GNOME before. Even after the GNOME Foundation got in touch with them, they insisted and filed more trademark applications [1][2][3].
We have to file formal proceedings to oppose 10 of these trademark applications by December 3, 2014. We will need 80k USD to oppose the registration of the first set of 10 applications. Thus, we need your help to raise these funds!
I already donated and hope you will too! Please, help us by donating today and spread the word through social media using the hashtag #defendGNOME!
GNOME can accept donations by paypal, check, bank/wire transfer, Flattr and Bitcoin.
Felipe Borges: Help GNOME defend its trademark against Groupon
11 de Novembro de 2014, 13:34 - sem comentários aindaRecently Groupon announced a new tablet-based platform named “GNOME”. If you’re reading this, you probably already know that GNOME has been a big and popular free software project for the past 17 years, *and a registered trademark since 2006*.
It’s outrageous that a billion dollars company such as Groupon would not have heard of GNOME before. Even after the GNOME Foundation got in touch with them, they insisted and filed more trademark applications [1][2][3].
We have to file formal proceedings to oppose 10 of these trademark applications by December 3, 2014. We will need 80k USD to oppose the registration of the first set of 10 applications. Thus, we need your help to raise these funds!
I already donated and hope you will too! Please, help us by donating today and spread the word through social media using the hashtag #defendGNOME!
GNOME can accept donations by paypal, check, bank/wire transfer, Flattr and Bitcoin.
Gustavo Noronha (kov): Yay, the left won! Or did it?
10 de Novembro de 2014, 21:38 - sem comentários aindaOriginally published on politi.kov
I have been asked by a bunch of friends from outside of Brazil for my opinion regarding the recent elections we had in Brazil, and it is a bit complicated to explain it without some background, so I decided to write this piece providing a bit of history so that people can understand my opinion.
The elections this year were a rematch of our traditional polarization between the workers party (PT) and the social democracy party (PSDB), which has been going on since 1994. PT and PSDB used to be allies. In the 80s, when the dictatorship dropped the law that forbade more than 2 parties, the opposition party, MDB, began breaking up in several smaller ones.
PSDB was founded by politicians and intelectuals who were inspired by Europe’s social democracy and political systems. Parliamentarism, for instance, is one of the historical causes of the party. The workers party had a more grassroots origin, with union leaders, marxist intelectuals and marxist-inspired catholic priests being the main founders. They drew their inspiration from the USSR and Cuba, and were very close to social movements.
Some people have celebrated the reelection of Dilma Roussef as a victory of the left against the right. In my opinion that view is wrong for several reasons. First, because I disagree that PSDB and Aécio Neves in particular are right-wing, both in terms of economics and social/moral issues. Second, because I believe Dilma’s first government has taken a quite severe turn to the right in several topics that matter a lot to me. Since comparisons with PSDB’s government during the 90s has been one of the main strategies of the campaign this year, I’ll argue why I think it was actually a pretty good government with a lot of left in it.
Unlike what happens in most other places, Brazil does not really have an actual right-wing party, economics-wise. Although we might see the birth of a couple in the near future, no current party is really against public health, education and social security being provided by the state as rights, or wants to decrease state size and lower taxes significantly. It should come as no surprise that even though it has undergone a lot of liberal reforms over the last 20 years, Brazil is still a very closed country, with very high import tariffs and a huge presence of the state in the economy. There is a certain consensus about all of that, with disagreements being essentially on implementation details, not goals.
On the other hand, and contrary to popular belief, when it comes to social and moral issues we are a very conservative people. Ironically, the two parties which have been in power over the last 20 years are quite progressive, being historically proponents of diversity, minorities rights, reproductive rights. They have had to compromise on those causes to become viable alternatives, given the conservative nature of the majority of the voters.
Despite their different origins and beliefs, both parties share socialist inclinations and were allies from the onset. That changed in 1992, when president Collor, who had been elected on a runoff against Lula (who PSDB supported), was impeached by Congress for corruption. With no formal political support and a chaotic situation in his hands, Itamar Franco, the vice president, called for a “national union” government to go through the last two years of his term. PSDB answered the call, but the workers party decided against being part of the government.
Fernando Henrique Cardoso, a sociologist who was one of the leaders of PSDB was chosen to lead the Foreign Relations Ministry, but a few months later got nominated to the Economy. At the time, Brazil lived under hyperinflation of close to 1000% a year, and several stabilization plans had been attempted. Economy Ministers did not last very much in office at the time. FHC gathered a team of economists and sponsored their stabilization plan, which turned out to be highly successful: the Plano Real (“Real Plan”). In addition to introducing a new currency, something that was becoming pretty common to Brazilians by then, it also attacked the structural causes of inflation.
Lula was counting on the failure of the Plano Real when he ran against FHC in 1994, but the plan succeeded, giving FHC two terms as president. During those two terms, FHC introduced several institutional changes that made Brazil a saner country. In addition to the hyperinflation, Brazil had lived a debt crises for decades and was still in default. FHC’s team renegotiated the debts, reopened lines of credit, but most importantly, introduced reforms that made the Brazilian finances and financial system credible.
The problem was not even that Brazil had a fiscal déficit, it just did not have any control whatsoever of money supply and budget. Banks, regardless of whether they were private or public, had very little regulation and took advantage of the hyperinflation to hide monstrous holes in their balances. When inflation was gone and regulation became more strict, those became apparent, and it was pretty clear that the system would collapse if nothing was done.
Some people like to say that FHC was a president who ruled for the rich and didn’t care about the poor. I think the way the potential collapse of the banking system was handled is a great counter-example of that. The government passed laws that made the owners of the banks responsible for the financial problems, regardless of whether caused by mismanagement or fraud. If a bank went under, the central bank intervened and added enough money to protect the deposits, but that money was a loan that had to be repaid by the owners of the bank, and the owners’ properties were added as collateral to the loan. As a brazilian journalist once said, the people did not risk losing their deposits, the bankers did risk losing the banks, though. Today, we have a separate fund, filled with money from the banks, that does what the central bank did back then when required.
Compare that to countries where the banking system was saved with tax payer money and executives kept getting huge bonuses regardless, while owners kept their profits. It is hard to find an initiative that is more focused on the public interest against the interest of the rich people who caused the problem. This legislation, called PROER, is still in place today, and it came along with solid regulation of the banking system. It should come as no surprise that Brazil went through the financial crisis of 2008 with not a single hiccup of the banking system and no fear of bank runs. Despite having been against PROER back in the day, Lula celebrated its existence in 2008, when it was clear it was one of the reasons we would not suffer much. He even advertised it as something that should be adopted by the US and Europe.
It is also pretty common to hear that under FHC social questions were not a priority. I believe it is pretty simple to see that that was not the case both by inspecting the growth of social spending and the improvement of social indicators for the period, such as UN’s human development index. One area in which people are particularly critical of the FHC government is the investment on higher education, and they are actually quite right. Brazil has free Federal universities and those did not get a lot of priority in the 90s. However, I would argue that while it is a matter of priorities, it is not one of education versus something else, but rather of what to invest on inside education. The reality is basic education was the priority.
When FHC came to power, Brazil had a significant number of children who were not going to school at all. The goal was to make access to schools universal for young children, and that goal was reached. Every child has been going to school since the early 2000s, and that is a significant achievement which reaches the poorest. While the federal universities are attended essentially by the Brazilian elite, given the difficulty of passing the exams and the relative lack of quality of free public schools compared to private ones, which is still a reality to this day, investment on getting children to even go to school for the early years has a significant impact on the lives of the poorest.
It is important to remember that getting every child to go to school is also what gave birth to one of the most celebrated programs from the Lula era: Bolsa Família (“Family Allowance”) is a direct money transfer to poor families, particularly those who have children and has been an important contribution to lowering inequality and getting people out of extreme poverty. To get the money, the families need to ensure their children are 1) attending school and 2) getting vaccinated.
That program comes from the FHC government, in which it was created with the name Bolsa Escola (“School Allowance”), in its turn inspired by a program of the same name by governor Cristovam Buarque, from PT. What Lula did, and he deserves a lot of credit for this, was to merge a series of smaller programs with Bolsa Escola, and then expand the program to ensure it got to more and more people. Interestingly, during the announcement of the program he credited the idea of doing that to a state governor from PSDB. You can see why I think these two should be allies again.
When faced with all these arguments, people will eventually say that FHC was bad because he privatized companies and used orthodox economic policies. Well, if that is what it takes, then we’ll have to take Lula down with him, because his first term was essentially a continuation of FHC’s second term: orthodox economic policies to keep inflation down, along with privatization of several state-owned companies and banks. But Lula, whom I voted for and whose government I believe was a good one, is not my subject: Dilma is.
On Lula’s second term, Dilma gained a lot of power when other major leaders of PT went down for corruption. She became second in command and started leading several programs. A big believer in developmentalism, she started pushing for a bigger role of the state in the coordination of the productive sector, with a clear focus on growing the industrial base.
One of the initiatives she sponsored was a sizable increase on the number and size of subsidized loans given out by the national development bank (BNDES). Brazil started an unnofficial “national champions” program, where the government elected a few big companies to get a huge amount of subsidized credit.
The goal was for these selected firms to get big enough to be competitive on the global market. The criteria for the choices is completely opaque, if it even exists, and includes handing out milions in subsidized credit for Eike Batista, who became Brazil’s richest enterpreneur for a while, and lost pretty much everything when it became clear the oil would not be pumping out of his camps after all, sinking with them a huge amount of public funds invested by BNDES.
The way this policy was enacted, it is unclear how much it really costs in terms of public funds: the Brazilian treasury emits debt to capitalize, lends that money to BNDES with higher than market interest, and BNDES then lends it out to the big companies with a lower than market interest rate. Although it is obviously unsustainable, the problem does not yet show in the balance because the grace period for BNDES debt with the treasury is 2040. The fact that this has a cost and, perhaps more importantly, a huge opportunity cost is not clear because it is not part of the government budget. Why are we putting money in this rather than quadrupling Bolsa Família, which studies show generates 1,78 reais in PIB for every 1 real invested? Worse, why are we not even updating Bolsa Família enough to cover inflation?
When Dilma got elected in 2010, the first signs were pretty bad. She was already seen as someone who did not care much for the environment, and on her first month in power she made good on that promise by pushing to get the Belo Monte Dam building started as soon as possible regardless of conditionalities being satisfied. To this day there are several issues with how the building of the dam is going: the handling of the indigenous people and the small city nearby are lacking, conditionalities are not met.
Beyond Belo Monte, indigenous leaders are being assassinated, deforestation in the Amazon forest has increased by 122% in 2014 alone. Dilma’s answer to people who question her on these kinds of issues is essentially: “would you rather not have electric power?”
Her populist authoritarian nature and obsession with industry are also pretty evident when it comes to her policies in the energy area as a whole. She showed up in national tv on the eve of our independence day celebration to announce a reduction in electric tariffs, mainly for industry, but also for homes. Nobody really knew how. The following week she sent a fast-track project to Congress to automatically renew concessions of power grid operators, requiring those who accepted it to lower tariffs, instead of doing an auction, which was already necessary anyway because the concessions were up on 2015. There was no discussion with stakeholders, there was just a populist announcement and a great deal of rhethoric to paint anyone who opposed as being against the people.
And now, everything went into the crapper because that represented a breach of contract that required indemnification, and we had a pretty bad drought that made power more expensive given the need to turn on the thermal generators. Combining the costs of the thermal generation, indemnity, and financial fallout that the grid operators suffered, we are already at 105 billion reais and counting, nobody knows how high the cost will reach. Any reduction in tariffs has long been invalidated. And the fact that industry has lowered production significantly ends up being good news, we would probably be under rationing already if that was not the case.
You would expect someone who fought a dictatorship to be pretty good in terms of human and civil rights. What we see in reality is a lack of respect for those things. During the world cup, Dilma has put the army on the streets and has supported arbitrary behaviour from state polices throughout the country. They jailed a bunch of demonstrators preemptively. No shit. The would be demonstrators were kept in jail throghout the tournament under false accusations. Dilma’s Minister of Justice said several times that the case against them was solid and that the arrests were legal, but it turned out the case simply did not exist. Just this week we had a number of executions orchestrated by policemen in the state of Pará and there is zero reaction from the federal government.
In the oil industry, Dilma has enacted a policy of subsidizing gas prices by using a fixed price that used to be lower than the international prices (it is no longer the case with the fall in international prices). That would not be a problem if Brazil was selfsufficient in oild and gas, which we are not: we had to import a significant amount of both. The implicit subsidy cost Petrobrás a huge amount of cash – the more gas it sold, the bigger the losses. This lead not only to decreasing the company’s market value (it is a state-controlled, but open company), but to reducing its capacity of investment as well.
That is more problematic than it sounds because, with our current concession model, every single oil camp needs to have Petrobrás as a member of the consortium. Limiting the company’s investment capacity limits the rate at which our pre-salt oil camps can be explored and thus the speed at which we can become selfsufficient. Chicken and egg anyone?
To make things worse, Dilma has made policies that lowered taxes on car production, used to foster economic activity during the crisis in 2008-2010, essentially permanent. This lead to a significant increase in traffic and polution on Brazilian cities, while at the same time increasing the pressure on Petrobrás, which had to import more and more gas. Meanwhile, Brazilian cities suffer from a severe lack of mobility infrastructure. A recent study has shown that Brazil has spend almost twice as much subsidized money on pro-car policies than on pro-mass transit projects. Talk about good usage of public funds.
One of the only remaining good news the government was still able to mention was the constant reduction in extreme poverty. Dilma was actually ellected promising to erradicate extreme poverty and changed the government’s slogan to “A rich country is a country with no poverty” (País rico é país sem pobreza). Well, it turns out all of these policies caused inequality and extreme poverty both to stop falling as of 2013. And given the policies were actually deepened in 2014, I believe it is very likely we’ll see an increase in both when we get the data for 2014, next year.
Other than that, her policies ended up being a complete failure. Despite giving tax benefits to several sectors, investment has fallen, growth has fallen and inflation is quite high at 6,6% for the last 12 months. In terms of minorities, her government has been a severe set back, with the government going back on educational material against homophoby saying it would not do “advertisement of sexual choice”, and going back on a decree that allowed the public health system to perform abortions on the cases allowed by the law (essentially if the woman has been raped).
Looking at Dilma’s policies, I really can’t see that much of the left, honestly. So why, you might ask, has this victory been deemed a victory of the left over the right? My explanation is the aura the workers party still manages to keep over itself. There’s a notion that whatever PT does, it will still be more to the left than PSDB, which I think is just crazy.
There is also a fair amount of idealizing Dilma just because she is Lula’s protegé. People will forgive anything, provided it is the workers party doing it. Thankfully, the number of people aligned on the left that supported the candidate from PSDB this election tells me this is changing quite rapidly. Hopefully that leads to PT having to reinvent itself, and get in touch with the left again.
Vicente Aguiar: Um Trabalho a Troco de nada? A resposta da comunidade GNOME para Jô Soares e Bill Gates à luz da teoria da Dádiva
11 de Outubro de 2014, 16:02 - sem comentários aindaSete anos após uma apresentação feita no IV Fórum GNOME em 2007 com esse mesmo título, finalmente, eu consegui publicar, em parceria com Genauto França Filho (meu orientador de Doutorado), o resultado da pesquisa que tentou responder uma questão que ronda o ecossistema dos projetos de software livre: "quem pode se permitir fazer um trabalho profissional a troco de nada?" Mais especificamente, esse artigo foi publicado na revista (acadêmica) Sociologias - uma publicação quadrimestral do Programa de Pós-Graduação em Sociologia da UFRGS, destinada a promover intercâmbio entre cientistas sociais.
No entanto, é importante ressaltar que essa questão norteadora da nossa pesquisa foi, inicialmente, levantada por Biil Gates na histórica "Carta Aberta aos Hobbistas" escrita em 1976 - um ano depois da fundação da então "Micro-Soft". Além dele, quatro décadas depois, mais especificamente em outubro de 2006, ela foi "remixada" por Jô Soares, no seu programa de televisão. Em uma de suas entrevistas, ao ser informado pelo Sérgio Amadeu (Prof. da UFABC) e pelo Júlio Neves (Prof. da UNiRio) sobre um possível engajamento voluntário de hackers ligados ao projetos de software livre, Jô Soares ressalta que, na visão dele, "por trás do fato do que é dado (software) de graça há uma intenção de ser vendido. (...) ou é um pessoal que é tudo monge Franciscano?"
O ponto de partida desse que escrevemos na Sociologias é que ainda são poucos os estudos que procuram analisar as características e a natureza desse novo contexto digital (de relações mediadas por dispositivos móveis como computadores, tablets e celulares) para além de um entendimento que tem como base apenas as noções de uma racionalidade utilitária ou do simples interesse econômico. Afinal, podemos dizer que mais recorrente do que esse tipo de pergunta é o tipo de resposta comum (e apressada) que diz que "ninguém trabalha de graça" ou que "sempre há um interesse financeiro nisso tudo".
Para evitar os limites de uma única forma de resposta "apressada" (para não dizer "equivocada") e, com isso, restringir a compreensão sobre a ação dos hackers nesses projetos, avaliamos que era importante respondê-la com um olhar mais científico e aprofundado. Assim, realizamos uma análise mais qualitativa sobre esse "fenômeno" que se apoiou em uma pesquisa de dois anos na comunidade do Projeto GNOME. Essa pesquisa resultou então na minha dissertação de mestrado na UFBA, em um dos capítulos do livro "Software Livre, Cultura Hacker e Ecossistema da Colaboração" e agora nesse artigo publicado na Revista Sociologias.
Membros da Comunidade GNOME por Louis Villa
Em termos de publicação, o diferencial então dessa edição v. 16, n. 36 (2014) da Revista Sociologias é o resgate da obra maussiana que fundamentou conceitualmente essa pesquisa sobre o Projeto GNOME - e, agora, serve também de base do meu projeto de Doutorado. Esse resgaste se dá no contexto de surgimento de uma crítica anti-utilitarista dentro do universo das ciências sociais contemporâneas, a qual foi concretizada pela fundação do MAUSS (Movimento Anti-Utilitarista nas Ciências Sociais).
Contudo, vale ressaltar que esse paradigma sociológico da dádiva busca ir além: mais do que a importância da sua vertente analítica, o MAUSS demonstra ser uma corrente sociológica implicada com a produção de pesquisas que se desenvolve a partir de um paradigma basilar, não apenas nas sociedade tradicionais como também para a sociedade contemporânea: a vida associativa e, em especial, a tripla ação de compartilhar, receber e retribuir. Vale então conferir essa edição da Sociologia da Dádiva na íntegra.
Lucas Rocha: Probing with Gradle
7 de Outubro de 2014, 20:12 - sem comentários aindaUp until now, Probe relied on dynamic view proxies generated at runtime to intercept View calls. Although very convenient, this approach greatly affects the time to inflate your layouts—which limits the number of use cases for the library, especially in more complex apps.
This is all changing now with Probe’s brand new Gradle plugin which seamlessly generates build-time proxies for your app. This means virtually no overhead at runtime!
Using Probe’s Gradle plugin is very simple. First, add the Gradle plugin as a dependency in your build script.
buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.13.+' classpath 'org.lucasr.probe:gradle-plugin:0.1.2' } }
Then add Probe’s library as a dependency in your app.
repositories { mavenCentral() } dependencies { compile 'org.lucasr.probe:probe:0.1.2' }
Next, apply the plugin to your app’s build.gradle.
apply plugin: 'probe'
Probe’s proxy generation is disabled by default and needs to be explicitly enabled on specific build variants (build type + product flavour). For example, this is how you enable Probe proxies in debug builds.
probe { buildVariants { debug { enabled = true } } }
And that’s all! You should now be able to deploy interceptors on any part of your UI. Here’s how you could deploy an OvermeasureInterceptor in an activity.
public final class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { Probe.deploy(this, new OvermeasureInterceptor()); super.onCreate(savedInstanceState); setContentView(R.id.main_activity); } }
While working on this feature, I have changed DexMaker to be an optional dependency i.e. you have to explicitly add DexMaker as a build dependency in your app in order to use it.
This is my first Gradle plugin. There’s definitely a lot of room for improvement here. These features are available in the 0.1.2 release in Maven Central.
As usual, feedback, bug reports, and fixes are very welcome. Enjoy!
Jonh Wendell: Recovering lost files after a git reset –hard
2 de Outubro de 2014, 13:31 - sem comentários aindaThis morning I’ve messed things up in my env…
I did a commit yesterday and thought I had pushed it, but not.
Today I did a git pull and was asked to do a merge, because there were changes in the remote.
I totally ignored this (don’t ask me why, perhaps absence of coffee…) and did a git reset –hard HEAD^^
So, yep, I lost my commit that existed only in my machine (this commit in particular was a file addition).
After blaming myself a lot, and a bit of google search, I’ve found this amazing blog post: http://zsoltfabok.com/blog/2012/06/recover-deleted-files-with-git/
I’m summarizing here the steps to have your commit (in my case, the file) back:
git fsck --no-reflog
This command will return a hash for the lost commit, something like
dangling commit fafeade9f348b18f37835ab49dab40172efde693
You can use this hash to do a checkout, for instance, and recover your file. \o/
So, let’s have a bit of coffee now
Jonh Wendell: Recovering lost files after a git reset –hard
2 de Outubro de 2014, 10:31 - sem comentários aindaThis morning I’ve messed things up in my env…
I did a commit yesterday and thought I had pushed it, but not.
Today I did a git pull and was asked to do a merge, because there were changes in the remote.
I totally ignored this (don’t ask me why, perhaps absence of coffee…) and did a git reset –hard HEAD^^
So, yep, I lost my commit that existed only in my machine (this commit in particular was a file addition).
After blaming myself a lot, and a bit of google search, I’ve found this amazing blog post: http://zsoltfabok.com/blog/2012/06/recover-deleted-files-with-git/
I’m summarizing here the steps to have your commit (in my case, the file) back:
git fsck --no-reflog
This command will return a hash for the lost commit, something like
dangling commit fafeade9f348b18f37835ab49dab40172efde693
You can use this hash to do a checkout, for instance, and recover your file. \o/
So, let’s have a bit of coffee now
Jonh Wendell: Moving on
1 de Outubro de 2014, 14:36 - sem comentários ainda[ENGLISH]
Hi guys, I’d like to share with you the news that my family and some friends already know: Since last month I’m not working at Intel anymore.
For those whom don’t know my history, I’ll summarize it here:
- About 3 years ago I left my home city to the biggest one in Brazil (São Paulo) to experience a full time Linux job
- The instability of my department at the time led me to look for another job; Then I got that opportunity at Intel
- Intel OTC office is located in Campinas (120km far away from São Paulo)
- After more than one year having to travel about 240km every day I had to make a decision: Move to Campinas or leave Intel.
It was not an easy decision. I have a family and I didn’t want to affect them again with a city change. On the other side, Intel is a great company and people at OTC Campinas are amazing.
So, two weeks ago I started working for an IT Security company, working again with Embedded Linux and with Open Source technologies. Oh, 8km (15 min) far from my home :).
That’s it, I hope to blog a bit more now, as I used to do in the past. See you!
[PORTUGUÊS]
Oi gente, gostaria de compartilhar uma novidade com vocês, que minha família e alguns amigos já sabem: Desde o mês passado que eu não trabalho mais na Intel.
Pra quem não conhece minha história, vou resumir aqui:
- Cerca de 3 anos atrás eu mudei de Maceió, minha cidade natal pra São Paulo, pra trabalhar exclusivamente com Linux
- Alguns problemas no meu departamento me levaram a buscar outro trabalho; Aí que entra a Intel
- O escritório onde fui alocado (OTC, Open Source Technology Center) fica em Campinas, distante 120km de São Paulo
- Depois de mais de 1 ano viajando cerca de 240km todos os dias eu tinha que tomar uma decisão: Mudar pra Campinas ou sair da Intel
Com certeza não foi uma decisão fácil. Tenho uma família e não queria afetá-los com mais uma mudança de cidade. Por outro lado, a Intel é uma ótima empresa e o pessoal do OTC Campinas é ótimo.
Então… duas semanas atrás comecei a trabalhar para uma empresa de segurança em TI, voltei a trabalhar com Linux embarcado e com Open Source de fato. Ah, e a 8km (15min) de casa :).
É isso, gente. Espero voltar a blogar com mais frequencia, como no passado. Até mais!
Lucas Rocha: New Features in Picasso
23 de Setembro de 2014, 12:52 - sem comentários aindaI’ve always been a big fan of Picasso, the Android image loading library by the Square folks. It provides some powerful features with a rather simple API.
Recently, I started working on a set of new features for Picasso that will make it even more awesome: request handlers, request management, and request priorities. These features have all been merged to the main repo now. Let me give you a quick overview of what they enable you to do.
Request Handlers
Picasso supports a wide variety of image sources, from simple resources to content providers, network, and more. Sometimes though, you need to load images in unconventional ways that are not supported by default in Picasso.
Wouldn’t it be nice if you could easily integrate your custom image loading logic with Picasso? That’s what the new request handlers are about. All you need to do is subclass RequestHandler and implement a couple of methods. For example:
public class PonyRequestHandler extends RequestHandler { private static final String PONY_SCHEME = "pony"; @Override public boolean canHandleRequest(Request data) { return PONY_SCHEME.equals(data.uri.getScheme()); } @Override public Result load(Request data) { return new Result(somePonyBitmap, MEMORY); } }
Then you register your request handler when instantiating Picasso:
Picasso picasso = new Picasso.Builder(context) .addRequestHandler(new PonyHandler()) .build();
Voilà! Now Picasso can handle pony URIs:
Picasso.with(context) .load("pony://somePonyName") .into(someImageView)
This pull request also involved rewriting all built-in bitmap loaders on top of the new API. This means you can also override the built-in request handlers if you need to.
Request Management
Even though Picasso handles view recycling, it does so in an inefficient way. For instance, if you do a fling gesture on a ListView, Picasso will still keep triggering and canceling requests blindly because there was no way to make it pause/resume requests according to the user interaction. Not anymore!
The new request management APIs allow you to tag associated requests that should be managed together. You can then pause, resume, or cancel requests associated with specific tags. The first thing you have to do is tag your requests as follows:
Picasso.with(context) .load("http://example.com/image.jpg") .tag(someTag) .into(someImageView)
Then you can pause and resume requests with this tag based on, say, the scroll state of a ListView. For example, Picasso’s sample app now has the following scroll listener:
public class SampleScrollListener implements AbsListView.OnScrollListener { ... @Override public void onScrollStateChanged(AbsListView view, int scrollState) { Picasso picasso = Picasso.with(context); if (scrollState == SCROLL_STATE_IDLE || scrollState == SCROLL_STATE_TOUCH_SCROLL) { picasso.resumeTag(someTag); } else { picasso.pauseTag(someTag); } } ... }
These APIs give you a much finer control over your image requests. The scroll listener case is just the canonical use case.
Request Priorities
It’s very common for images in your Android UI to have different priorities. For instance, you may want to give higher priority to the big hero image in your activity in relation to other secondary images in the same screen.
Up until now, there was no way to hint Picasso about the relative priorities between images. The new priority API allows you to tell Picasso about the intended order of your image requests. You can just do:
Picasso.with(context) .load("http://example.com/image.jpg") .priority(HIGH) .into(someImageView);
These priorities don’t guarantee a specific order, they just tilt the balance towards higher-priority requests.
That’s all for now. Big thanks to Jake Wharton and Dimitris Koutsogiorgas for the prompt code and API reviews!
You can try these new APIs now by fetching the latest Picasso code on Github. These features will probably be available in the 2.4 release. Enjoy!
Lucas Rocha: Introducing Probe
16 de Setembro de 2014, 7:32 - sem comentários aindaWe’ve all heard of the best practices regarding layouts on Android: keep your view tree as simple as possible, avoid multi-pass layouts high up in the hierarchy, etc. But the truth is, it’s pretty hard to see what’s actually going on in your view tree in each platform traversal (measure → layout → draw).
We’re well served with developer options for tracking graphics performance—debug GPU overdraw, show hardware layers updates, profile GPU rendering, and others. However, there is a big gap in terms of development tools for tracking layout traversals and figuring out how your layouts actually behave. This is why I created Probe.
Probe is a small library that allows you to intercept view method calls during Android’s layout traversals e.g. onMeasure(), onLayout(), onDraw(), etc. Once a method call is intercepted, you can either do extra things on top of the view’s original implementation or completely override the method on-the-fly.
Using Probe is super simple. All you have to do is implement an Interceptor. Here’s an interceptor that completely overrides a view’s onDraw(). Calling super.onDraw() would call the view’s original implementation.
public class DrawGreen extends Interceptor { private final Paint mPaint; public DrawGreen() { mPaint = new Paint(); mPaint.setColor(Color.GREEN); } @Override public void onDraw(View view, Canvas canvas) { canvas.drawPaint(mPaint); } }
Then deploy your Interceptor by inflating your layout with a Probe:
Probe probe = new Probe(this, new DrawGreen(), new Filter.ViewId(R.id.view2)); View root = probe.inflate(R.layout.main_activity, null);
Just to give you an idea of the kind of things you can do with Probe, I’ve already implemented a couple of built-in interceptors. OvermeasureInterceptor tints views according to the number of times they got measured in a single traversal i.e. equivalent to overdraw but for measurement.
LayoutBoundsInterceptor is equivalent to Android’s “Show layout bounds” developer option. The main difference is that you can show bounds only for specific views.
Under the hood, Probe uses Google’s DexMaker to generate dynamic View proxies during layout inflation. The stock ProxyBuilder implementation was not good enough for Probe because I wanted avoid using reflection entirely after the proxy classes were generated. So I created a specialized View proxy builder that generates proxy classes tailored for Probe’s use case.
This means Probe takes longer than your usual LayoutInflater to inflate layout resources. There’s no use of reflection after layout inflation though. Your views should perform the same. For now, Probe is meant to be a developer tool only and I don’t recommend using it in production.
The code is available on Github. As usual, contributions are very welcome.