FlatCAMApp.py 328 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import urllib.request, urllib.parse, urllib.error
  9. import getopt
  10. import random
  11. import simplejson as json
  12. import lzma
  13. from stat import S_IREAD, S_IRGRP, S_IROTH
  14. import subprocess
  15. import tkinter as tk
  16. from PyQt5 import QtPrintSupport
  17. import urllib.request, urllib.parse, urllib.error
  18. from contextlib import contextmanager
  19. import gc
  20. from xml.dom.minidom import parseString as parse_xml_string
  21. ########################################
  22. ## Imports part of FlatCAM ##
  23. ########################################
  24. from ObjectCollection import *
  25. from FlatCAMObj import *
  26. from flatcamGUI.PlotCanvas import *
  27. from flatcamGUI.FlatCAMGUI import *
  28. from FlatCAMCommon import LoudDict
  29. from FlatCAMPostProc import load_postprocessors
  30. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  31. from FlatCAMProcess import *
  32. from FlatCAMWorkerStack import WorkerStack
  33. from flatcamGUI.VisPyVisuals import Color
  34. from vispy.gloo.util import _screenshot
  35. from vispy.io import write_png
  36. from flatcamTools import *
  37. from multiprocessing import Pool
  38. import tclCommands
  39. import gettext
  40. import FlatCAMTranslation as fcTranslate
  41. fcTranslate.apply_language('strings')
  42. import builtins
  43. if '_' not in builtins.__dict__:
  44. _ = gettext.gettext
  45. ########################################
  46. ## App ##
  47. ########################################
  48. class App(QtCore.QObject):
  49. """
  50. The main application class. The constructor starts the GUI.
  51. """
  52. # Get Cmd Line Options
  53. cmd_line_shellfile = ''
  54. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  55. try:
  56. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  57. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  58. except getopt.GetoptError:
  59. print(cmd_line_help)
  60. sys.exit(2)
  61. for opt, arg in cmd_line_options:
  62. if opt == '-h':
  63. print(cmd_line_help)
  64. sys.exit()
  65. elif opt == '--shellfile':
  66. cmd_line_shellfile = arg
  67. # Logging ##
  68. log = logging.getLogger('base')
  69. log.setLevel(logging.DEBUG)
  70. # log.setLevel(logging.WARNING)
  71. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  72. handler = logging.StreamHandler()
  73. handler.setFormatter(formatter)
  74. log.addHandler(handler)
  75. # Version
  76. version = 8.913
  77. version_date = "2019/03/23"
  78. beta = True
  79. # current date now
  80. date = str(datetime.today()).rpartition(' ')[0]
  81. # URL for update checks and statistics
  82. version_url = "http://flatcam.org/version"
  83. # App URL
  84. app_url = "http://flatcam.org"
  85. # Manual URL
  86. manual_url = "http://flatcam.org/manual/index.html"
  87. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  88. should_we_quit = True
  89. # this variable will hold the project status
  90. # if True it will mean that the project was modified and not saved
  91. should_we_save = False
  92. ##################
  93. ## Signals ##
  94. ##################
  95. # Inform the user
  96. # Handled by:
  97. # * App.info() --> Print on the status bar
  98. inform = QtCore.pyqtSignal(str)
  99. # General purpose background task
  100. worker_task = QtCore.pyqtSignal(dict)
  101. # File opened
  102. # Handled by:
  103. # * register_folder()
  104. # * register_recent()
  105. # Note: Setting the parameters to unicode does not seem
  106. # to have an effect. Then are received as Qstring
  107. # anyway.
  108. # File type and filename
  109. file_opened = QtCore.pyqtSignal(str, str)
  110. # File type and filename
  111. file_saved = QtCore.pyqtSignal(str, str)
  112. # Percentage of progress
  113. progress = QtCore.pyqtSignal(int)
  114. plots_updated = QtCore.pyqtSignal()
  115. # Emitted by new_object() and passes the new object as argument, plot flag.
  116. # on_object_created() adds the object to the collection, plots on appropriate flag
  117. # and emits new_object_available.
  118. object_created = QtCore.pyqtSignal(object, bool, bool)
  119. # Emitted when a object has been changed (like scaled, mirrored)
  120. object_changed = QtCore.pyqtSignal(object)
  121. # Emitted after object has been plotted.
  122. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  123. object_plotted = QtCore.pyqtSignal(object)
  124. # Emitted when a new object has been added or deleted from/to the collection
  125. object_status_changed = QtCore.pyqtSignal(object, str)
  126. message = QtCore.pyqtSignal(str, str, str)
  127. # Emmited when shell command is finished(one command only)
  128. shell_command_finished = QtCore.pyqtSignal(object)
  129. # Emitted when multiprocess pool has been recreated
  130. pool_recreated = QtCore.pyqtSignal(object)
  131. # Emitted when an unhandled exception happens
  132. # in the worker task.
  133. thread_exception = QtCore.pyqtSignal(object)
  134. def __init__(self, user_defaults=True, post_gui=None):
  135. """
  136. Starts the application.
  137. :return: app
  138. :rtype: App
  139. """
  140. App.log.info("FlatCAM Starting...")
  141. ###################
  142. ### OS-specific ###
  143. ###################
  144. # Folder for user settings.
  145. if sys.platform == 'win32':
  146. from win32com.shell import shell, shellcon
  147. if platform.architecture()[0] == '32bit':
  148. App.log.debug("Win32!")
  149. else:
  150. App.log.debug("Win64!")
  151. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\FlatCAM'
  152. self.os = 'windows'
  153. else: # Linux/Unix/MacOS
  154. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  155. self.os = 'unix'
  156. ###############################
  157. ### Setup folders and files ###
  158. ###############################
  159. if not os.path.exists(self.data_path):
  160. os.makedirs(self.data_path)
  161. App.log.debug('Created data folder: ' + self.data_path)
  162. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  163. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  164. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  165. if not os.path.exists(self.postprocessorpaths):
  166. os.makedirs(self.postprocessorpaths)
  167. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  168. # create current_defaults.FlatConfig file if there is none
  169. try:
  170. f = open(self.data_path + '/current_defaults.FlatConfig')
  171. f.close()
  172. except IOError:
  173. App.log.debug('Creating empty current_defaults.FlatConfig')
  174. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  175. json.dump({}, f)
  176. f.close()
  177. # create factory_defaults.FlatConfig file if there is none
  178. try:
  179. f = open(self.data_path + '/factory_defaults.FlatConfig')
  180. f.close()
  181. except IOError:
  182. App.log.debug('Creating empty factory_defaults.FlatConfig')
  183. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  184. json.dump({}, f)
  185. f.close()
  186. try:
  187. f = open(self.data_path + '/recent.json')
  188. f.close()
  189. except IOError:
  190. App.log.debug('Creating empty recent.json')
  191. f = open(self.data_path + '/recent.json', 'w')
  192. json.dump([], f)
  193. f.close()
  194. # Application directory. CHDIR to it. Otherwise, trying to load
  195. # GUI icons will fail as their path is relative.
  196. # This will fail under cx_freeze ...
  197. self.app_home = os.path.dirname(os.path.realpath(__file__))
  198. App.log.debug("Application path is " + self.app_home)
  199. App.log.debug("Started in " + os.getcwd())
  200. # cx_freeze workaround
  201. if os.path.isfile(self.app_home):
  202. self.app_home = os.path.dirname(self.app_home)
  203. os.chdir(self.app_home)
  204. # Create multiprocessing pool
  205. self.pool = Pool()
  206. # variable to store mouse coordinates
  207. self.mouse = [0, 0]
  208. ####################
  209. ## Initialize GUI ##
  210. ####################
  211. # FlatCAM colors used in plotting
  212. self.FC_light_green = '#BBF268BF'
  213. self.FC_dark_green = '#006E20BF'
  214. self.FC_light_blue = '#a5a5ffbf'
  215. self.FC_dark_blue = '#0000ffbf'
  216. QtCore.QObject.__init__(self)
  217. self.ui = FlatCAMGUI(self.version, self.beta, self)
  218. # self.connect(self.ui,
  219. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  220. # self.save_geometry) PyQt4
  221. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  222. self.ui.final_save.connect(self.final_save)
  223. ##############
  224. #### Data ####
  225. ##############
  226. self.recent = []
  227. self.clipboard = QtWidgets.QApplication.clipboard()
  228. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  229. self.project_filename = None
  230. self.toggle_units_ignore = False
  231. # self.defaults_form = PreferencesUI()
  232. # when adding entries here read the comments in the method found bellow named:
  233. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  234. self.defaults_form_fields = {
  235. # General App
  236. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  237. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  238. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  239. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  240. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  241. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  242. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  243. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  244. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  245. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  246. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  247. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  248. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  249. # General GUI Preferences
  250. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  251. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  252. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  253. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  254. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  255. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  256. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  257. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  258. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  259. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  260. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  261. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  262. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  263. # General GUI Settings
  264. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  265. # Gerber General
  266. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  267. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  268. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  269. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  270. # Gerber Options
  271. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  272. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  273. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  274. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  275. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  276. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  277. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  278. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  279. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  280. # Gerber Advanced Options
  281. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  282. "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  283. "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  284. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  285. # Excellon General
  286. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  287. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  288. "excellon_format_upper_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  289. "excellon_format_lower_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  290. "excellon_format_upper_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  291. "excellon_format_lower_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  292. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  293. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  294. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  295. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  296. # Excellon Options
  297. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  298. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  299. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  300. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  301. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  302. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  303. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  304. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  305. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  306. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  307. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  308. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  309. # Excellon Advanced Options
  310. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  311. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  312. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  313. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  314. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  315. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  316. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  317. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  318. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  319. # Excellon Export
  320. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  321. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  322. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  323. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  324. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  325. # Geometry General
  326. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  327. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  328. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  329. # Geometry Options
  330. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  331. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  332. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  333. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  334. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  335. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  336. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  337. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  338. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  339. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  340. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  341. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  342. # Geometry Advanced Options
  343. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  344. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  345. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  346. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  347. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  348. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  349. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  350. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  351. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  352. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  353. # CNCJob General
  354. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  355. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  356. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  357. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  358. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  359. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  360. # CNC Job Options
  361. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  362. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  363. # CNC Job Advanced Options
  364. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  365. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  366. # NCC Tool
  367. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  368. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  369. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  370. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  371. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  372. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  373. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  374. # CutOut Tool
  375. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  376. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  377. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  378. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  379. # Paint Area Tool
  380. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  381. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  382. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  383. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  384. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  385. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  386. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  387. # 2-sided Tool
  388. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  389. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  390. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  391. # Film Tool
  392. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  393. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  394. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  395. # Panelize Tool
  396. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  397. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  398. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  399. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  400. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  401. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  402. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  403. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  404. # Calculators Tool
  405. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  406. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  407. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  408. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  409. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  410. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  411. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  412. # Transformations Tool
  413. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  414. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  415. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  416. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  417. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  418. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  419. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  420. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  421. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  422. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  423. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  424. # SolderPaste Dispensing Tool
  425. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  426. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  427. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  428. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  429. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  430. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  431. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  432. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  433. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  434. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  435. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  436. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  437. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  438. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  439. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  440. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo
  441. }
  442. #############################
  443. #### LOAD POSTPROCESSORS ####
  444. #############################
  445. self.postprocessors = load_postprocessors(self)
  446. for name in list(self.postprocessors.keys()):
  447. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  448. if name.partition('_')[0] == 'Paste':
  449. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  450. continue
  451. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  452. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  453. if name == 'hpgl':
  454. continue
  455. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  456. #############################
  457. #### LOAD LANGUAGES ####
  458. #############################
  459. self.languages = fcTranslate.load_languages()
  460. for name in sorted(self.languages.values()):
  461. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  462. self.defaults = LoudDict()
  463. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  464. self.defaults.update({
  465. # Global APP Preferences
  466. "global_serial": 0,
  467. "global_stats": {},
  468. "units": "IN",
  469. "global_app_level": 'b',
  470. "global_language": 'English',
  471. "global_version_check": True,
  472. "global_send_stats": True,
  473. "global_pan_button": '2',
  474. "global_mselect_key": 'Control',
  475. "global_project_at_startup": False,
  476. "global_project_autohide": True,
  477. "global_toggle_tooltips": True,
  478. "global_compression_level": 3,
  479. "global_save_compressed": True,
  480. # Global GUI Preferences
  481. "global_gridx": 0.0393701,
  482. "global_gridy": 0.0393701,
  483. "global_snap_max": 0.001968504,
  484. "global_workspace": False,
  485. "global_workspaceT": "A4P",
  486. "global_grid_context_menu": {
  487. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  488. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  489. },
  490. "global_plot_fill": '#BBF268BF',
  491. "global_plot_line": '#006E20BF',
  492. "global_sel_fill": '#a5a5ffbf',
  493. "global_sel_line": '#0000ffbf',
  494. "global_alt_sel_fill": '#BBF268BF',
  495. "global_alt_sel_line": '#006E20BF',
  496. "global_draw_color": '#FF0000',
  497. "global_sel_draw_color": '#0000FF',
  498. "global_toolbar_view": 127,
  499. "global_background_timeout": 300000, # Default value is 5 minutes
  500. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  501. # (python trace only for unknown errors),
  502. # 1 = show trace(show trace allways),
  503. # 2 = (For the future).
  504. # Persistence
  505. "global_last_folder": None,
  506. "global_last_save_folder": None,
  507. # Default window geometry
  508. "global_def_win_x": 100,
  509. "global_def_win_y": 100,
  510. "global_def_win_w": 1024,
  511. "global_def_win_h": 650,
  512. # Constants...
  513. "global_defaults_save_period_ms": 20000, # Time between default saves.
  514. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  515. "global_shell_at_startup": False, # Show the shell at startup.
  516. "global_recent_limit": 10, # Max. items in recent list.
  517. "fit_key": 'V',
  518. "zoom_out_key": '-',
  519. "zoom_in_key": '=',
  520. "grid_toggle_key": 'G',
  521. "zoom_ratio": 1.5,
  522. "global_point_clipboard_format": "(%.4f, %.4f)",
  523. "global_zdownrate": None,
  524. # General GUI Settings
  525. "global_hover": True,
  526. # Gerber General
  527. "gerber_plot": True,
  528. "gerber_solid": True,
  529. "gerber_multicolored": False,
  530. "gerber_isotooldia": 0.016,
  531. "gerber_isopasses": 1,
  532. "gerber_isooverlap": 0.15,
  533. # Gerber Options
  534. "gerber_combine_passes": False,
  535. "gerber_milling_type": "cl",
  536. "gerber_noncoppermargin": 0.1,
  537. "gerber_noncopperrounded": False,
  538. "gerber_bboxmargin": 0.1,
  539. "gerber_bboxrounded": False,
  540. "gerber_circle_steps": 64,
  541. "gerber_use_buffer_for_union": True,
  542. # Gerber Advanced Options
  543. "gerber_aperture_display": False,
  544. "gerber_aperture_scale_factor": 1.0,
  545. "gerber_aperture_buffer_factor": 0.0,
  546. "gerber_follow": False,
  547. # Excellon General
  548. "excellon_plot": True,
  549. "excellon_solid": True,
  550. "excellon_format_upper_in": 2,
  551. "excellon_format_lower_in": 4,
  552. "excellon_format_upper_mm": 3,
  553. "excellon_format_lower_mm": 3,
  554. "excellon_zeros": "L",
  555. "excellon_units": "INCH",
  556. "excellon_optimization_type": 'B',
  557. "excellon_search_time": 3,
  558. # Excellon Options
  559. "excellon_drillz": -0.1,
  560. "excellon_travelz": 0.1,
  561. "excellon_feedrate": 3.0,
  562. "excellon_spindlespeed": None,
  563. "excellon_dwell": False,
  564. "excellon_dwelltime": 1,
  565. "excellon_toolchange": False,
  566. "excellon_toolchangez": 1.0,
  567. "excellon_ppname_e": 'default',
  568. "excellon_tooldia": 0.016,
  569. "excellon_slot_tooldia": 0.016,
  570. "excellon_gcode_type": "drills",
  571. # Excellon Advanced Options
  572. "excellon_offset": 0.0,
  573. "excellon_toolchangexy": "0.0, 0.0",
  574. "excellon_startz": None,
  575. "excellon_endz": 2.0,
  576. "excellon_feedrate_rapid": 3.0,
  577. "excellon_z_pdepth": -0.02,
  578. "excellon_feedrate_probe": 3.0,
  579. "excellon_f_plunge": False,
  580. "excellon_f_retract": False,
  581. # Excellon Export
  582. "excellon_exp_units": 'INCH',
  583. "excellon_exp_format": 'ndec',
  584. "excellon_exp_integer": 2,
  585. "excellon_exp_decimals": 4,
  586. "excellon_exp_zeros": 'LZ',
  587. # Geometry General
  588. "geometry_plot": True,
  589. "geometry_circle_steps": 64,
  590. "geometry_cnctooldia": 0.016,
  591. # Geometry Options
  592. "geometry_cutz": -0.002,
  593. "geometry_multidepth": False,
  594. "geometry_depthperpass": 0.002,
  595. "geometry_travelz": 0.1,
  596. "geometry_toolchange": False,
  597. "geometry_toolchangez": 1.0,
  598. "geometry_feedrate": 3.0,
  599. "geometry_feedrate_z": 3.0,
  600. "geometry_spindlespeed": None,
  601. "geometry_dwell": False,
  602. "geometry_dwelltime": 1,
  603. "geometry_ppname_g": 'default',
  604. # Geometry Advanced Options
  605. "geometry_toolchangexy": "0.0, 0.0",
  606. "geometry_startz": None,
  607. "geometry_endz": 2.0,
  608. "geometry_feedrate_rapid": 3.0,
  609. "geometry_extracut": False,
  610. "geometry_z_pdepth": -0.02,
  611. "geometry_f_plunge": False,
  612. "geometry_feedrate_probe": 3.0,
  613. "geometry_segx": 0.0,
  614. "geometry_segy": 0.0,
  615. # CNC Job General
  616. "cncjob_plot": True,
  617. "cncjob_plot_kind": 'all',
  618. "cncjob_tooldia": 0.0393701,
  619. "cncjob_coords_decimals": 4,
  620. "cncjob_fr_decimals": 2,
  621. "cncjob_steps_per_circle": 64,
  622. # CNC Job Options
  623. "cncjob_prepend": "",
  624. "cncjob_append": "",
  625. # CNC Job Advanced Options
  626. "cncjob_toolchange_macro": "",
  627. "cncjob_toolchange_macro_enable": False,
  628. "tools_ncctools": "0.0393701, 0.019685",
  629. "tools_nccoverlap": 0.015748,
  630. "tools_nccmargin": 0.00393701,
  631. "tools_nccmethod": "seed",
  632. "tools_nccconnect": True,
  633. "tools_ncccontour": True,
  634. "tools_nccrest": False,
  635. "tools_cutouttooldia": 0.00393701,
  636. "tools_cutoutmargin": 0.00393701,
  637. "tools_cutoutgapsize": 0.005905512,
  638. "tools_gaps_ff": "8",
  639. "tools_painttooldia": 0.07,
  640. "tools_paintoverlap": 0.15,
  641. "tools_paintmargin": 0.0,
  642. "tools_paintmethod": "seed",
  643. "tools_selectmethod": "single",
  644. "tools_pathconnect": True,
  645. "tools_paintcontour": True,
  646. "tools_2sided_mirror_axis": "X",
  647. "tools_2sided_axis_loc": "point",
  648. "tools_2sided_drilldia": 0.0393701,
  649. "tools_film_type": 'neg',
  650. "tools_film_boundary": 0.0393701,
  651. "tools_film_scale": 0,
  652. "tools_panelize_spacing_columns": 0,
  653. "tools_panelize_spacing_rows": 0,
  654. "tools_panelize_columns": 1,
  655. "tools_panelize_rows": 1,
  656. "tools_panelize_constrain": False,
  657. "tools_panelize_constrainx": 0.0,
  658. "tools_panelize_constrainy": 0.0,
  659. "tools_panelize_panel_type": 'gerber',
  660. "tools_calc_vshape_tip_dia": 0.007874,
  661. "tools_calc_vshape_tip_angle": 30,
  662. "tools_calc_vshape_cut_z": 0.000787,
  663. "tools_calc_electro_length": 10.0,
  664. "tools_calc_electro_width": 10.0,
  665. "tools_calc_electro_cdensity":13.0,
  666. "tools_calc_electro_growth": 10.0,
  667. "tools_transform_rotate": 90,
  668. "tools_transform_skew_x": 0.0,
  669. "tools_transform_skew_y": 0.0,
  670. "tools_transform_scale_x": 1.0,
  671. "tools_transform_scale_y": 1.0,
  672. "tools_transform_scale_link": True,
  673. "tools_transform_scale_reference": True,
  674. "tools_transform_offset_x": 0.0,
  675. "tools_transform_offset_y": 0.0,
  676. "tools_transform_mirror_reference": False,
  677. "tools_transform_mirror_point": (0, 0),
  678. "tools_solderpaste_tools": "0.0393701, 0.011811",
  679. "tools_solderpaste_new": 0.011811,
  680. "tools_solderpaste_z_start": 0.00019685039,
  681. "tools_solderpaste_z_dispense": 0.00393701,
  682. "tools_solderpaste_z_stop": 0.00019685039,
  683. "tools_solderpaste_z_travel": 0.00393701,
  684. "tools_solderpaste_z_toolchange": 0.0393701,
  685. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  686. "tools_solderpaste_frxy": 3.0,
  687. "tools_solderpaste_frz": 3.0,
  688. "tools_solderpaste_frz_dispense": 0.0393701,
  689. "tools_solderpaste_speedfwd": 20,
  690. "tools_solderpaste_dwellfwd": 1,
  691. "tools_solderpaste_speedrev": 10,
  692. "tools_solderpaste_dwellrev": 1,
  693. "tools_solderpaste_pp": 'Paste_1'
  694. })
  695. ###############################
  696. ### Load defaults from file ###
  697. ###############################
  698. if user_defaults:
  699. self.load_defaults(filename='current_defaults')
  700. ############################
  701. ##### APPLY APP LANGUAGE ###
  702. ############################
  703. ret_val = fcTranslate.apply_language('strings')
  704. if ret_val == "no language":
  705. self.inform.emit(_("[ERROR] Could not find the Language files. The App strings are missing."))
  706. log.debug("Could not find the Language files. The App strings are missing.")
  707. else:
  708. # make the current language the current selection on the language combobox
  709. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  710. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  711. ###################################
  712. ### CREATE UNIQUE SERIAL NUMBER ###
  713. ###################################
  714. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  715. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  716. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  717. self.save_defaults(silent=True)
  718. self.propagate_defaults(silent=True)
  719. self.restore_main_win_geom()
  720. def auto_save_defaults():
  721. try:
  722. self.save_defaults(silent=True)
  723. self.propagate_defaults(silent=True)
  724. finally:
  725. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  726. # the following lines activates automatic defaults save
  727. # if user_defaults:
  728. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  729. # self.options_form = PreferencesUI()
  730. self.options_form_fields = {
  731. "units": self.ui.general_options_form.general_app_group.units_radio,
  732. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  733. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  734. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  735. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  736. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  737. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  738. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  739. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  740. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  741. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  742. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  743. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  744. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  745. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  746. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  747. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  748. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  749. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  750. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  751. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  752. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  753. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  754. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  755. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  756. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  757. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  758. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  759. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  760. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  761. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  762. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  763. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  764. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  765. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  766. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  767. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  768. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  769. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  770. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  771. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  772. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  773. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  774. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  775. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  776. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  777. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  778. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  779. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  780. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  781. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  782. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  783. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  784. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  785. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  786. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  787. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  788. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  789. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  790. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  791. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  792. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  793. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  794. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  795. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  796. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  797. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  798. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  799. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  800. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  801. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  802. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  803. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  804. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  805. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  806. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  807. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  808. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  809. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  810. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  811. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  812. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  813. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  814. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  815. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  816. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  817. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  818. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  819. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  820. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  821. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  822. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  823. }
  824. for name in list(self.postprocessors.keys()):
  825. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  826. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  827. self.options = LoudDict()
  828. self.options.set_change_callback(self.on_options_dict_change)
  829. self.options.update({
  830. "units": "IN",
  831. "global_gridx": 1.0,
  832. "global_gridy": 1.0,
  833. "global_snap_max": 0.05,
  834. "global_background_timeout": 300000, # Default value is 5 minutes
  835. "global_verbose_error_level": 0, # Shell verbosity:
  836. # 0 = default(python trace only for unknown errors),
  837. # 1 = show trace(show trace allways), 2 = (For the future).
  838. "gerber_plot": True,
  839. "gerber_solid": True,
  840. "gerber_multicolored": False,
  841. "gerber_isotooldia": 0.016,
  842. "gerber_isopasses": 1,
  843. "gerber_isooverlap": 0.15,
  844. "gerber_combine_passes": True,
  845. "gerber_noncoppermargin": 0.0,
  846. "gerber_noncopperrounded": False,
  847. "gerber_bboxmargin": 0.0,
  848. "gerber_bboxrounded": False,
  849. "excellon_plot": True,
  850. "excellon_solid": False,
  851. "excellon_format_upper_in": 2,
  852. "excellon_format_lower_in": 4,
  853. "excellon_format_upper_mm": 3,
  854. "excellon_format_lower_mm": 3,
  855. "excellon_units": 'INCH',
  856. "excellon_optimization_type": 'B',
  857. "excellon_search_time": 3,
  858. "excellon_zeros": "L",
  859. "excellon_drillz": -0.1,
  860. "excellon_travelz": 0.1,
  861. "excellon_feedrate": 3.0,
  862. "excellon_feedrate_rapid": 3.0,
  863. "excellon_spindlespeed": None,
  864. "excellon_dwell": True,
  865. "excellon_dwelltime": 1000,
  866. "excellon_toolchange": False,
  867. "excellon_toolchangez": 1.0,
  868. "excellon_toolchangexy": "0.0, 0.0",
  869. "excellon_tooldia": 0.016,
  870. "excellon_ppname_e": 'default',
  871. "excellon_f_plunge": False,
  872. "excellon_startz": None,
  873. "excellon_endz": 2.0,
  874. "geometry_plot": True,
  875. "geometry_segx": 0.0,
  876. "geometry_segy": 0.0,
  877. "geometry_cutz": -0.002,
  878. "geometry_travelz": 0.1,
  879. "geometry_feedrate": 3.0,
  880. "geometry_feedrate_z": 3.0,
  881. "geometry_feedrate_rapid": 3.0,
  882. "geometry_spindlespeed": None,
  883. "geometry_dwell": True,
  884. "geometry_dwelltime": 1000,
  885. "geometry_cnctooldia": 0.016,
  886. "geometry_toolchange": False,
  887. "geometry_toolchangez": 2.0,
  888. "geometry_toolchangexy": "0.0, 0.0",
  889. "geometry_startz": None,
  890. "geometry_endz": 2.0,
  891. "geometry_ppname_g": "default",
  892. "geometry_f_plunge": False,
  893. "geometry_depthperpass": 0.002,
  894. "geometry_multidepth": False,
  895. "geometry_extracut": False,
  896. "cncjob_plot": True,
  897. "cncjob_tooldia": 0.016,
  898. "cncjob_prepend": "",
  899. "cncjob_append": "",
  900. "tools_ncctools": "1.0, 0.5",
  901. "tools_nccoverlap": 0.4,
  902. "tools_nccmargin": 1,
  903. "tools_cutouttooldia": 0.07,
  904. "tools_cutoutmargin": 0.1,
  905. "tools_cutoutgapsize": 0.15,
  906. "tools_gaps_ff": "8",
  907. "tools_painttooldia": 0.07,
  908. "tools_paintoverlap": 0.15,
  909. "tools_paintmargin": 0.0,
  910. "tools_paintmethod": "seed",
  911. "tools_selectmethod": "single",
  912. "tools_pathconnect": True,
  913. "tools_paintcontour": True,
  914. "tools_2sided_mirror_axis": "X",
  915. "tools_2sided_axis_loc": 'point',
  916. "tools_2sided_drilldia": 1,
  917. "tools_film_type": 'neg',
  918. "tools_film_boundary": 1,
  919. "tools_film_scale": 0,
  920. "tools_panelize_spacing_columns": 0,
  921. "tools_panelize_spacing_rows": 0,
  922. "tools_panelize_columns": 1,
  923. "tools_panelize_rows": 1,
  924. "tools_panelize_constrain": False,
  925. "tools_panelize_constrainx": 0.0,
  926. "tools_panelize_constrainy": 0.0
  927. })
  928. self.options.update(self.defaults) # Copy app defaults to project options
  929. self.gen_form = None
  930. self.ger_form = None
  931. self.exc_form = None
  932. self.geo_form = None
  933. self.cnc_form = None
  934. self.tools_form = None
  935. self.on_options_combo_change(0) # Will show the initial form
  936. ### Define OBJECT COLLECTION ###
  937. self.collection = ObjectCollection(self)
  938. self.ui.project_tab_layout.addWidget(self.collection.view)
  939. ###
  940. self.log.debug("Finished creating Object Collection.")
  941. ### Initialize the color box's color in Preferences -> Global -> Color
  942. # Init Plot Colors
  943. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  944. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  945. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  946. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  947. int(self.defaults['global_plot_fill'][7:9], 16))
  948. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  949. int(self.defaults['global_plot_fill'][7:9], 16))
  950. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  951. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  952. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  953. # Init Left-Right Selection colors
  954. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  955. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  956. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  957. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  958. int(self.defaults['global_sel_fill'][7:9], 16))
  959. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  960. int(self.defaults['global_sel_fill'][7:9], 16))
  961. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  962. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  963. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  964. # Init Right-Left Selection colors
  965. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  966. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  967. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  968. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  969. int(self.defaults['global_sel_fill'][7:9], 16))
  970. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  971. int(self.defaults['global_sel_fill'][7:9], 16))
  972. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  973. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  974. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  975. # Init Draw color and Selection Draw Color
  976. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  977. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  978. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  979. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  980. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  981. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  982. #### End of Data ####
  983. #### Plot Area ####
  984. start_plot_time = time.time() # debug
  985. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  986. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  987. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  988. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  989. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  990. # Keys over plot enabled
  991. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  992. self.ui.splitter.setStretchFactor(1, 2)
  993. # So it can receive key presses
  994. self.plotcanvas.vispy_canvas.native.setFocus()
  995. self.app_cursor = self.plotcanvas.new_cursor()
  996. self.app_cursor.enabled = False
  997. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  998. # depending on from where those tools are called different actions can be done
  999. self.call_source = 'app'
  1000. end_plot_time = time.time()
  1001. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1002. ### EDITOR section
  1003. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1004. self.exc_editor = FlatCAMExcEditor(self)
  1005. #### Adjust tabs width ####
  1006. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1007. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1008. self.collection.view.setMinimumWidth(290)
  1009. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  1010. #### Worker ####
  1011. self.workers = WorkerStack()
  1012. self.worker_task.connect(self.workers.add_task)
  1013. ### Signal handling ###
  1014. ## Custom signals
  1015. self.inform.connect(self.info)
  1016. self.message.connect(self.message_dialog)
  1017. self.progress.connect(self.set_progress_bar)
  1018. self.object_created.connect(self.on_object_created)
  1019. self.object_changed.connect(self.on_object_changed)
  1020. self.object_plotted.connect(self.on_object_plotted)
  1021. self.plots_updated.connect(self.on_plots_updated)
  1022. self.file_opened.connect(self.register_recent)
  1023. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1024. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1025. ## Standard signals
  1026. # Menu
  1027. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1028. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1029. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1030. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1031. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1032. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1033. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1034. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1035. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1036. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1037. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1038. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1039. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1040. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1041. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1042. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1043. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1044. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1045. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1046. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1047. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1048. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1049. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1050. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  1051. self.ui.menueditedit.triggered.connect(self.object2editor)
  1052. self.ui.menueditok.triggered.connect(self.editor2object)
  1053. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1054. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1055. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1056. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1057. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1058. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1059. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1060. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  1061. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1062. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1063. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1064. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1065. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1066. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1067. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1068. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1069. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1070. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1071. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1072. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1073. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1074. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1075. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1076. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1077. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1078. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1079. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1080. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1081. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1082. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1083. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1084. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1085. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1086. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1087. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1088. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1089. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1090. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1091. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1092. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1093. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1094. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1095. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1096. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1097. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  1098. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1099. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1100. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1101. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1102. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1103. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1104. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1105. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1106. # ToolBar signals
  1107. self.connect_toolbar_signals()
  1108. # Context Menu
  1109. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1110. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1111. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1112. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1113. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  1114. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  1115. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  1116. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  1117. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  1118. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  1119. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  1120. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1121. self.ui.clearplot.triggered.connect(self.clear_plots)
  1122. self.ui.replot.triggered.connect(self.plot_all)
  1123. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1124. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1125. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1126. self.ui.popmenu_save.triggered.connect(self.editor2object)
  1127. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1128. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1129. # Preferences Plot Area TAB
  1130. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1131. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1132. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1133. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1134. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1135. ###############################
  1136. ### GUI PREFERENCES SIGNALS ###
  1137. ###############################
  1138. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1139. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1140. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1141. )
  1142. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(self.on_toggle_units)
  1143. ###############################
  1144. ### GUI PREFERENCES SIGNALS ###
  1145. ###############################
  1146. # Setting plot colors signals
  1147. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  1148. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  1149. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  1150. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  1151. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  1152. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  1153. # Setting selection (left - right) colors signals
  1154. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  1155. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  1156. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  1157. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  1158. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  1159. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  1160. # Setting selection (right - left) colors signals
  1161. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  1162. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  1163. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1164. self.on_alt_sf_color_spinner)
  1165. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1166. self.on_alt_sf_color_slider)
  1167. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  1168. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  1169. # Setting Editor Draw colors signals
  1170. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  1171. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  1172. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  1173. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  1174. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1175. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1176. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1177. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1178. self.on_cnc_custom_parameters)
  1179. # Modify G-CODE Plot Area TAB
  1180. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1181. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1182. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1183. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1184. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1185. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1186. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1187. # Object list
  1188. self.collection.view.activated.connect(self.on_row_activated)
  1189. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1190. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1191. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1192. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1193. self.on_excellon_defaults_button)
  1194. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1195. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1196. self.on_excellon_options_button)
  1197. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1198. self.tool_tab_locked = False
  1199. # decide if to show or hide the Notebook side of the screen at startup
  1200. if self.defaults["global_project_at_startup"] is True:
  1201. self.ui.splitter.setSizes([1, 1])
  1202. else:
  1203. self.ui.splitter.setSizes([0, 1])
  1204. ####################
  1205. ### Other setups ###
  1206. ####################
  1207. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1208. self.setup_obj_classes()
  1209. self.setup_recent_items()
  1210. self.setup_component_editor()
  1211. #############
  1212. ### Shell ###
  1213. #############
  1214. ###
  1215. # Auto-complete KEYWORDS
  1216. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1217. 'aligndrill', 'clear',
  1218. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1219. 'export_gcode',
  1220. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1221. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1222. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1223. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1224. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1225. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1226. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1227. ]
  1228. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1229. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1230. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1231. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1232. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1233. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1234. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1235. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1236. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1237. ]
  1238. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1239. self.shell = FCShell(self, version=self.version)
  1240. self.shell._edit.set_model_data(self.myKeywords)
  1241. self.shell.setWindowIcon(self.ui.app_icon)
  1242. self.shell.setWindowTitle("FlatCAM Shell")
  1243. self.shell.resize(*self.defaults["global_shell_shape"])
  1244. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1245. self.shell.append_output("(Type help to get started)\n\n")
  1246. self.init_tcl()
  1247. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1248. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1249. self.ui.shell_dock.setWidget(self.shell)
  1250. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1251. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1252. QtWidgets.QDockWidget.DockWidgetFloatable |
  1253. QtWidgets.QDockWidget.DockWidgetClosable)
  1254. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1255. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1256. if self.defaults["global_shell_at_startup"]:
  1257. self.ui.shell_dock.show()
  1258. else:
  1259. self.ui.shell_dock.hide()
  1260. #########################
  1261. ### Tools and Plugins ###
  1262. #########################
  1263. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1264. self.install_tools()
  1265. ### System Font Parsing ###
  1266. # self.f_parse = ParseFont(self)
  1267. # self.parse_system_fonts()
  1268. # test if the program was started with a script as parameter
  1269. if self.cmd_line_shellfile:
  1270. try:
  1271. with open(self.cmd_line_shellfile, "r") as myfile:
  1272. cmd_line_shellfile_text = myfile.read()
  1273. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1274. except Exception as ext:
  1275. print("ERROR: ", ext)
  1276. sys.exit(2)
  1277. ###########################
  1278. #### Check for updates ####
  1279. ###########################
  1280. # Separate thread (Not worker)
  1281. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1282. if (self.beta is False or self.beta is None) and \
  1283. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1284. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1285. self.thr2 = QtCore.QThread()
  1286. self.worker_task.emit({'fcn': self.version_check,
  1287. 'params': []})
  1288. self.thr2.start()
  1289. ####################################
  1290. #### Variables for global usage ####
  1291. ####################################
  1292. # coordinates for relative position display
  1293. self.rel_point1 = (0, 0)
  1294. self.rel_point2 = (0, 0)
  1295. # variable to store coordinates
  1296. self.pos = (0, 0)
  1297. self.pos_jump = (0, 0)
  1298. # decide if we have a double click or single click
  1299. self.doubleclick = False
  1300. # variable to store if there was motion before right mouse button click (panning)
  1301. self.panning_action = False
  1302. # variable to store if a command is active (then the var is not None) and which one it is
  1303. self.command_active = None
  1304. # variable to store the status of moving selection action
  1305. # None value means that it's not an selection action
  1306. # True value = a selection from left to right
  1307. # False value = a selection from right to left
  1308. self.selection_type = None
  1309. # List to store the objects that are currently loaded in FlatCAM
  1310. # This list is updated on each object creation or object delete
  1311. self.all_objects_list = []
  1312. # List to store the objects that are selected
  1313. self.sel_objects_list = []
  1314. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1315. self.key_modifiers = None
  1316. # Variable to hold the status of the axis
  1317. self.toggle_axis = True
  1318. # Variable to store the status of the fullscreen event
  1319. self.toggle_fscreen = False
  1320. # Variable to store the status of the code editor
  1321. self.toggle_codeeditor = False
  1322. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1323. self.click_noproject = False
  1324. self.cursor = None
  1325. # Variable to store the GCODE that was edited
  1326. self.gcode_edited = ""
  1327. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1328. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1329. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1330. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1331. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1332. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1333. 'mpf']
  1334. self.svg_list = ['svg']
  1335. self.dxf_list = ['dxf']
  1336. self.prj_list = ['flatprj']
  1337. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1338. # flag for polygons not cleared
  1339. self.poly_not_cleared = False
  1340. # VisPy visuals
  1341. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.vispy_canvas.view.scene, layers=1)
  1342. self.isHovering = False
  1343. self.notHovering = True
  1344. ### Save defaults to factory_defaults.FlatConfig file ###
  1345. ### It's done only once after install #############
  1346. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1347. fac_def_from_file = factory_file.read()
  1348. factory_defaults = json.loads(fac_def_from_file)
  1349. # if the file contain an empty dictionary then save the factory defaults into the file
  1350. if not factory_defaults:
  1351. self.save_factory_defaults(silent=False)
  1352. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1353. initial_lay = 'Compact'
  1354. self.on_layout(index=None, lay=initial_lay)
  1355. # Set the combobox in Preferences to the current layout
  1356. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1357. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1358. factory_file.close()
  1359. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1360. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1361. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1362. # Post-GUI initialization: Experimental attempt
  1363. # to perform unit tests on the GUI.
  1364. # if post_gui is not None:
  1365. # post_gui(self)
  1366. App.log.debug("END of constructor. Releasing control.")
  1367. # accept a project file as command line parameter
  1368. # the path/file_name must be enclosed in quotes if it contain spaces
  1369. for argument in App.args:
  1370. if '.FlatPrj' in argument:
  1371. try:
  1372. project_name = str(argument)
  1373. if project_name == "":
  1374. self.inform.emit(_("Open cancelled."))
  1375. else:
  1376. # self.open_project(project_name)
  1377. run_from_arg = True
  1378. self.worker_task.emit({'fcn': self.open_project,
  1379. 'params': [project_name, run_from_arg]})
  1380. except Exception as e:
  1381. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1382. if '.FlatConfig' in argument:
  1383. try:
  1384. file_name = str(argument)
  1385. if file_name == "":
  1386. self.inform.emit(_("Open Config file failed."))
  1387. else:
  1388. # run_from_arg = True
  1389. # self.worker_task.emit({'fcn': self.open_config_file,
  1390. # 'params': [file_name, run_from_arg]})
  1391. self.open_config_file(file_name, run_from_arg=True)
  1392. except Exception as e:
  1393. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1394. if '.FlatScript' in argument:
  1395. try:
  1396. file_name = str(argument)
  1397. if file_name == "":
  1398. self.inform.emit(_("Open Script file failed."))
  1399. else:
  1400. # run_from_arg = True
  1401. # self.worker_task.emit({'fcn': self.open_script_file,
  1402. # 'params': [file_name, run_from_arg]})
  1403. self.on_filerunscript(name=file_name)
  1404. except Exception as e:
  1405. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1406. def defaults_read_form(self):
  1407. for option in self.defaults_form_fields:
  1408. try:
  1409. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1410. except:
  1411. pass
  1412. def defaults_write_form(self, factor=None):
  1413. for option in self.defaults:
  1414. self.defaults_write_form_field(option, factor=factor)
  1415. # try:
  1416. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1417. # except KeyError:
  1418. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1419. # # TODO: Rethink this?
  1420. # pass
  1421. def defaults_write_form_field(self, field, factor=None):
  1422. try:
  1423. if factor is None:
  1424. self.defaults_form_fields[field].set_value(self.defaults[field])
  1425. else:
  1426. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  1427. except KeyError:
  1428. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1429. # TODO: Rethink this?
  1430. pass
  1431. except AttributeError:
  1432. log.debug(field)
  1433. def clear_pool(self):
  1434. self.pool.close()
  1435. self.pool = Pool()
  1436. self.pool_recreated.emit(self.pool)
  1437. gc.collect()
  1438. # the order that the tools are installed is important as they can depend on each other install position
  1439. def install_tools(self):
  1440. self.dblsidedtool = DblSidedTool(self)
  1441. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1442. self.measurement_tool = Measurement(self)
  1443. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1444. self.panelize_tool = Panelize(self)
  1445. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1446. self.film_tool = Film(self)
  1447. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1448. self.paste_tool = SolderPaste(self)
  1449. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'), separator=True)
  1450. self.move_tool = ToolMove(self)
  1451. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1452. before=self.ui.menueditorigin)
  1453. self.cutout_tool = CutOut(self)
  1454. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  1455. before=self.measurement_tool.menuAction)
  1456. self.ncclear_tool = NonCopperClear(self)
  1457. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  1458. before=self.measurement_tool.menuAction, separator=True)
  1459. self.paint_tool = ToolPaint(self)
  1460. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1461. before=self.measurement_tool.menuAction, separator=True)
  1462. self.calculator_tool = ToolCalculator(self)
  1463. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1464. self.transform_tool = ToolTransform(self)
  1465. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1466. self.properties_tool = Properties(self)
  1467. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1468. self.image_tool = ToolImage(self)
  1469. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1470. separator=True)
  1471. self.log.debug("Tools are installed.")
  1472. def remove_tools(self):
  1473. for act in self.ui.menutool.actions():
  1474. self.ui.menutool.removeAction(act)
  1475. def init_tools(self):
  1476. log.debug("init_tools()")
  1477. # delete the data currently in the Tools Tab and the Tab itself
  1478. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1479. if widget is not None:
  1480. widget.deleteLater()
  1481. self.ui.notebook.removeTab(2)
  1482. # rebuild the Tools Tab
  1483. self.ui.tool_tab = QtWidgets.QWidget()
  1484. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1485. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1486. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1487. self.ui.tool_scroll_area = VerticalScrollArea()
  1488. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1489. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1490. # first remove all of them
  1491. self.remove_tools()
  1492. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1493. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1494. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1495. # third install all of them
  1496. self.install_tools()
  1497. self.log.debug("Tools are initialized.")
  1498. # def parse_system_fonts(self):
  1499. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1500. # 'params': []})
  1501. def connect_toolbar_signals(self):
  1502. # Toolbar
  1503. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1504. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1505. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1506. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1507. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1508. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1509. self.ui.replot_btn.triggered.connect(self.plot_all)
  1510. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1511. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1512. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1513. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1514. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1515. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1516. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  1517. self.ui.delete_btn.triggered.connect(self.on_delete)
  1518. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  1519. # Tools Toolbar Signals
  1520. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1521. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1522. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1523. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1524. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1525. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1526. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1527. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1528. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1529. def object2editor(self):
  1530. """
  1531. Send the current Geometry or Excellon object (if any) into the editor.
  1532. :return: None
  1533. """
  1534. self.report_usage("object2editor()")
  1535. # adjust the visibility of some of the canvas context menu
  1536. self.ui.popmenu_edit.setVisible(False)
  1537. self.ui.popmenu_save.setVisible(True)
  1538. # adjust the status of the menu entries related to the editor
  1539. self.ui.menueditedit.setDisabled(True)
  1540. self.ui.menueditok.setDisabled(False)
  1541. edited_object = self.collection.get_active()
  1542. if isinstance(edited_object, FlatCAMGeometry):
  1543. # for now, if the Geometry is MultiGeo do not allow the editing
  1544. if edited_object.multigeo is True:
  1545. self.inform.emit(_("[WARNING_NOTCL] Editing a MultiGeo Geometry is not possible for the moment."))
  1546. return
  1547. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1548. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1549. self.geo_editor.edit_fcgeometry(edited_object)
  1550. # we set the notebook to hidden
  1551. self.ui.splitter.setSizes([0, 1])
  1552. # set call source to the Editor we go into
  1553. self.call_source = 'geo_editor'
  1554. elif isinstance(edited_object, FlatCAMExcellon):
  1555. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1556. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1557. self.exc_editor.edit_fcexcellon(edited_object)
  1558. # set call source to the Editor we go into
  1559. self.call_source = 'exc_editor'
  1560. else:
  1561. self.inform.emit(_("[WARNING_NOTCL]Select a Geometry or Excellon Object to edit."))
  1562. return
  1563. # make sure that we can't select another object while in Editor Mode:
  1564. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1565. # delete any selection shape that might be active as they are not relevant in Editor
  1566. self.delete_selection_shape()
  1567. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1568. self.ui.plot_tab_area.protectTab(0)
  1569. self.inform.emit(_("[WARNING_NOTCL]Editor is activated ..."))
  1570. self.should_we_save = True
  1571. def editor2object(self):
  1572. """
  1573. Transfers the Geometry or Excellon from the editor to the current object.
  1574. :return: None
  1575. """
  1576. self.report_usage("editor2object()")
  1577. # adjust the status of the menu entries related to the editor
  1578. self.ui.menueditedit.setDisabled(False)
  1579. self.ui.menueditok.setDisabled(True)
  1580. # do not update a geometry or excellon object unless it comes out of an editor
  1581. if self.call_source != 'app':
  1582. # adjust the visibility of some of the canvas context menu
  1583. self.ui.popmenu_edit.setVisible(True)
  1584. self.ui.popmenu_save.setVisible(False)
  1585. edited_obj = self.collection.get_active()
  1586. obj_type = ""
  1587. if isinstance(edited_obj, FlatCAMGeometry):
  1588. obj_type = "Geometry"
  1589. self.geo_editor.update_fcgeometry(edited_obj)
  1590. self.geo_editor.update_options(edited_obj)
  1591. self.geo_editor.deactivate()
  1592. # update the geo object options so it is including the bounding box values
  1593. try:
  1594. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1595. edited_obj.options['xmin'] = xmin
  1596. edited_obj.options['ymin'] = ymin
  1597. edited_obj.options['xmax'] = xmax
  1598. edited_obj.options['ymax'] = ymax
  1599. except AttributeError:
  1600. self.inform.emit(_("[WARNING] Object empty after edit."))
  1601. elif isinstance(edited_obj, FlatCAMExcellon):
  1602. obj_type = "Excellon"
  1603. self.exc_editor.update_fcexcellon(edited_obj)
  1604. self.exc_editor.update_options(edited_obj)
  1605. self.exc_editor.deactivate()
  1606. else:
  1607. self.inform.emit(_("[WARNING_NOTCL]Select a Geometry or Excellon Object to update."))
  1608. return
  1609. # if notebook is hidden we show it
  1610. if self.ui.splitter.sizes()[0] == 0:
  1611. self.ui.splitter.setSizes([1, 1])
  1612. # restore the call_source to app
  1613. self.call_source = 'app'
  1614. edited_obj.plot()
  1615. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1616. self.ui.plot_tab_area.protectTab(0)
  1617. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  1618. # reset the Object UI to original settings
  1619. # edited_obj.set_ui(edited_obj.ui_type())
  1620. # edited_obj.build_ui()
  1621. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1622. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1623. def get_last_folder(self):
  1624. return self.defaults["global_last_folder"]
  1625. def get_last_save_folder(self):
  1626. loc = self.defaults["global_last_save_folder"]
  1627. if loc is None:
  1628. loc = self.defaults["global_last_folder"]
  1629. if loc is None:
  1630. loc = os.path.dirname(__file__)
  1631. return loc
  1632. def report_usage(self, resource):
  1633. """
  1634. Increments usage counter for the given resource
  1635. in self.defaults['global_stats'].
  1636. :param resource: Name of the resource.
  1637. :return: None
  1638. """
  1639. if resource in self.defaults['global_stats']:
  1640. self.defaults['global_stats'][resource] += 1
  1641. else:
  1642. self.defaults['global_stats'][resource] = 1
  1643. def init_tcl(self):
  1644. if hasattr(self,'tcl'):
  1645. # self.tcl = None
  1646. # TODO we need to clean non default variables and procedures here
  1647. # new object cannot be used here as it will not remember values created for next passes,
  1648. # because tcl was execudted in old instance of TCL
  1649. pass
  1650. else:
  1651. self.tcl = tk.Tcl()
  1652. self.setup_shell()
  1653. self.log.debug("TCL Shell has been initialized.")
  1654. # TODO: This shouldn't be here.
  1655. class TclErrorException(Exception):
  1656. """
  1657. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1658. """
  1659. pass
  1660. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  1661. """
  1662. Shows a message on the FlatCAM Shell
  1663. :param msg: Message to display.
  1664. :param show: Opens the shell.
  1665. :param error: Shows the message as an error.
  1666. :return: None
  1667. """
  1668. if show:
  1669. self.ui.shell_dock.show()
  1670. try:
  1671. if error:
  1672. self.shell.append_error(msg + "\n")
  1673. elif warning:
  1674. self.shell.append_warning(msg + "\n")
  1675. elif success:
  1676. self.shell.append_success(msg + "\n")
  1677. elif selected:
  1678. self.shell.append_selected(msg + "\n")
  1679. else:
  1680. self.shell.append_output(msg + "\n")
  1681. except AttributeError:
  1682. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1683. def raise_tcl_unknown_error(self, unknownException):
  1684. """
  1685. Raise exception if is different type than TclErrorException
  1686. this is here mainly to show unknown errors inside TCL shell console.
  1687. :param unknownException:
  1688. :return:
  1689. """
  1690. if not isinstance(unknownException, self.TclErrorException):
  1691. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1692. else:
  1693. raise unknownException
  1694. def display_tcl_error(self, error, error_info=None):
  1695. """
  1696. escape bracket [ with \ otherwise there is error
  1697. "ERROR: missing close-bracket" instead of real error
  1698. :param error: it may be text or exception
  1699. :return: None
  1700. """
  1701. if isinstance(error, Exception):
  1702. exc_type, exc_value, exc_traceback = error_info
  1703. if not isinstance(error, self.TclErrorException):
  1704. show_trace = 1
  1705. else:
  1706. show_trace = int(self.defaults['global_verbose_error_level'])
  1707. if show_trace > 0:
  1708. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1709. trc_formated = []
  1710. for a in reversed(trc):
  1711. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1712. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1713. exc_type,
  1714. "\n".join(trc_formated))
  1715. else:
  1716. text = "%s" % error
  1717. else:
  1718. text = error
  1719. text = text.replace('[', '\\[').replace('"', '\\"')
  1720. self.tcl.eval('return -code error "%s"' % text)
  1721. def raise_tcl_error(self, text):
  1722. """
  1723. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1724. :param text: text of error
  1725. :return: raise exception
  1726. """
  1727. self.display_tcl_error(text)
  1728. raise self.TclErrorException(text)
  1729. def exec_command(self, text):
  1730. """
  1731. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1732. Also handles execution in separated threads
  1733. :param text:
  1734. :return: output if there was any
  1735. """
  1736. self.report_usage('exec_command')
  1737. result = self.exec_command_test(text, False)
  1738. #MS: added this method call so the geometry is updated once the TCL
  1739. #command is executed
  1740. self.plot_all()
  1741. return result
  1742. def exec_command_test(self, text, reraise=True):
  1743. """
  1744. Same as exec_command(...) with additional control over exceptions.
  1745. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1746. :param text: Input command
  1747. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1748. :return: Output from the command
  1749. """
  1750. text = str(text)
  1751. try:
  1752. self.shell.open_proccessing() # Disables input box.
  1753. result = self.tcl.eval(str(text))
  1754. if result != 'None':
  1755. self.shell.append_output(result + '\n')
  1756. except tk.TclError as e:
  1757. # This will display more precise answer if something in TCL shell fails
  1758. result = self.tcl.eval("set errorInfo")
  1759. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1760. self.shell.append_error('ERROR: ' + result + '\n')
  1761. # Show error in console and just return or in test raise exception
  1762. if reraise:
  1763. raise e
  1764. finally:
  1765. self.shell.close_proccessing()
  1766. pass
  1767. return result
  1768. # """
  1769. # Code below is unsused. Saved for later.
  1770. # """
  1771. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1772. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1773. # self.log.debug(parts)
  1774. # try:
  1775. # if parts[0] not in commands:
  1776. # self.shell.append_error("Unknown command\n")
  1777. # return
  1778. #
  1779. # #import inspect
  1780. # #inspect.getargspec(someMethod)
  1781. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1782. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1783. # self.shell.append_error(
  1784. # "Command %s takes %d arguments. %d given.\n" %
  1785. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1786. # )
  1787. # return
  1788. #
  1789. # cmdfcn = commands[parts[0]]["fcn"]
  1790. # cmdconv = commands[parts[0]]["converters"]
  1791. # if len(parts) - 1 > 0:
  1792. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1793. # else:
  1794. # retval = cmdfcn()
  1795. # retfcn = commands[parts[0]]["retfcn"]
  1796. # if retval and retfcn(retval):
  1797. # self.shell.append_output(retfcn(retval) + "\n")
  1798. #
  1799. # except Exception as e:
  1800. # #self.shell.append_error(''.join(traceback.format_exc()))
  1801. # #self.shell.append_error("?\n")
  1802. # self.shell.append_error(str(e) + "\n")
  1803. def info(self, msg):
  1804. """
  1805. Informs the user. Normally on the status bar, optionally
  1806. also on the shell.
  1807. :param msg: Text to write.
  1808. :return: None
  1809. """
  1810. # Type of message in brackets at the begining of the message.
  1811. match = re.search("\[([^\]]+)\](.*)", msg)
  1812. if match:
  1813. level = match.group(1)
  1814. msg_ = match.group(2)
  1815. self.ui.fcinfo.set_status(str(msg_), level=level)
  1816. if level.lower() == "error":
  1817. self.shell_message(msg, error=True, show=True)
  1818. elif level.lower() == "warning":
  1819. self.shell_message(msg, warning=True, show=True)
  1820. elif level.lower() == "error_notcl":
  1821. self.shell_message(msg, error=True, show=False)
  1822. elif level.lower() == "warning_notcl":
  1823. self.shell_message(msg, warning=True, show=False)
  1824. elif level.lower() == "success":
  1825. self.shell_message(msg, success=True, show=False)
  1826. elif level.lower() == "selected":
  1827. self.shell_message(msg, selected=True, show=False)
  1828. else:
  1829. self.shell_message(msg, show=False)
  1830. else:
  1831. self.ui.fcinfo.set_status(str(msg), level="info")
  1832. # make sure that if the message is to clear the infobar with a space
  1833. # is not printed over and over on the shell
  1834. if msg != '':
  1835. self.shell_message(msg)
  1836. def restore_toolbar_view(self):
  1837. tb = self.defaults["global_toolbar_view"]
  1838. if tb & 1:
  1839. self.ui.toolbarfile.setVisible(True)
  1840. else:
  1841. self.ui.toolbarfile.setVisible(False)
  1842. if tb & 2:
  1843. self.ui.toolbargeo.setVisible(True)
  1844. else:
  1845. self.ui.toolbargeo.setVisible(False)
  1846. if tb & 4:
  1847. self.ui.toolbarview.setVisible(True)
  1848. else:
  1849. self.ui.toolbarview.setVisible(False)
  1850. if tb & 8:
  1851. self.ui.toolbartools.setVisible(True)
  1852. else:
  1853. self.ui.toolbartools.setVisible(False)
  1854. if tb & 16:
  1855. self.ui.exc_edit_toolbar.setVisible(True)
  1856. else:
  1857. self.ui.exc_edit_toolbar.setVisible(False)
  1858. if tb & 32:
  1859. self.ui.geo_edit_toolbar.setVisible(True)
  1860. else:
  1861. self.ui.geo_edit_toolbar.setVisible(False)
  1862. if tb & 64:
  1863. self.ui.snap_toolbar.setVisible(True)
  1864. else:
  1865. self.ui.snap_toolbar.setVisible(False)
  1866. if tb & 128:
  1867. self.ui.toolbarshell.setVisible(True)
  1868. else:
  1869. self.ui.toolbarshell.setVisible(False)
  1870. def load_defaults(self, filename):
  1871. """
  1872. Loads the aplication's default settings from current_defaults.FlatConfig into
  1873. ``self.defaults``.
  1874. :return: None
  1875. """
  1876. try:
  1877. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1878. options = f.read()
  1879. f.close()
  1880. except IOError:
  1881. self.log.error("Could not load defaults file.")
  1882. self.inform.emit(_("[ERROR] Could not load defaults file."))
  1883. # in case the defaults file can't be loaded, show all toolbars
  1884. self.defaults["global_toolbar_view"] = 255
  1885. return
  1886. try:
  1887. defaults = json.loads(options)
  1888. except:
  1889. # in case the defaults file can't be loaded, show all toolbars
  1890. self.defaults["global_toolbar_view"] = 255
  1891. e = sys.exc_info()[0]
  1892. App.log.error(str(e))
  1893. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  1894. return
  1895. self.defaults.update(defaults)
  1896. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1897. # restore the toolbar view
  1898. self.restore_toolbar_view()
  1899. def on_import_preferences(self):
  1900. """
  1901. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1902. ``self.defaults``.
  1903. :return: None
  1904. """
  1905. self.report_usage("on_import_preferences")
  1906. App.log.debug("on_import_preferences()")
  1907. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1908. try:
  1909. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1910. directory=self.data_path, filter=filter)
  1911. except TypeError:
  1912. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"), filter=filter)
  1913. filename = str(filename)
  1914. if filename == "":
  1915. self.inform.emit(_("[WARNING_NOTCL]FlatCAM preferences import cancelled."))
  1916. else:
  1917. try:
  1918. f = open(filename)
  1919. options = f.read()
  1920. f.close()
  1921. except IOError:
  1922. self.log.error("Could not load defaults file.")
  1923. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  1924. return
  1925. try:
  1926. defaults_from_file = json.loads(options)
  1927. except:
  1928. e = sys.exc_info()[0]
  1929. App.log.error(str(e))
  1930. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  1931. return
  1932. self.defaults.update(defaults_from_file)
  1933. self.inform.emit(_("[success]Imported Defaults from %s") %filename)
  1934. def on_export_preferences(self):
  1935. self.report_usage("on_export_preferences")
  1936. App.log.debug("on_export_preferences()")
  1937. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1938. try:
  1939. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  1940. caption=_("Export FlatCAM Preferences"),
  1941. directory=self.data_path + '/preferences_' + self.date.replace('-', ''), filter=filter
  1942. )
  1943. except TypeError:
  1944. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"), filter=filter)
  1945. filename = str(filename)
  1946. defaults_from_file = {}
  1947. if filename == "":
  1948. self.inform.emit(_("[WARNING_NOTCL]FlatCAM preferences export cancelled."))
  1949. return
  1950. else:
  1951. try:
  1952. f = open(filename, 'w')
  1953. defaults_file_content = f.read()
  1954. f.close()
  1955. except IOError:
  1956. App.log.debug('Creating a new preferences file ...')
  1957. f = open(filename, 'w')
  1958. json.dump({}, f)
  1959. f.close()
  1960. except:
  1961. e = sys.exc_info()[0]
  1962. App.log.error("Could not load defaults file.")
  1963. App.log.error(str(e))
  1964. self.inform.emit(_("[ERROR_NOTCL]Could not load defaults file."))
  1965. return
  1966. try:
  1967. defaults_from_file = json.loads(defaults_file_content)
  1968. except:
  1969. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1970. # Update options
  1971. self.defaults_read_form()
  1972. defaults_from_file.update(self.defaults)
  1973. self.propagate_defaults(silent=True)
  1974. # Save update options
  1975. try:
  1976. f = open(filename, "w")
  1977. json.dump(defaults_from_file, f)
  1978. f.close()
  1979. except:
  1980. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  1981. return
  1982. self.file_saved.emit("preferences", filename)
  1983. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1984. def on_preferences_open_folder(self):
  1985. self.report_usage("on_preferences_open_folder()")
  1986. if sys.platform == 'win32':
  1987. subprocess.Popen('explorer %s' % self.data_path)
  1988. elif sys.platform == 'darwin':
  1989. os.system('open "%s"' % self.data_path)
  1990. else:
  1991. subprocess.Popen(['xdg-open', self.data_path])
  1992. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1993. def save_geometry(self, x, y, width, height, notebook_width):
  1994. self.defaults["global_def_win_x"] = x
  1995. self.defaults["global_def_win_y"] = y
  1996. self.defaults["global_def_win_w"] = width
  1997. self.defaults["global_def_win_h"] = height
  1998. self.defaults["def_notebook_width"] = notebook_width
  1999. self.save_defaults()
  2000. def message_dialog(self, title, message, kind="info"):
  2001. icon = {"info": QtWidgets.QMessageBox.Information,
  2002. "warning": QtWidgets.QMessageBox.Warning,
  2003. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2004. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2005. dlg.setText(message)
  2006. dlg.exec_()
  2007. def register_recent(self, kind, filename):
  2008. self.log.debug("register_recent()")
  2009. self.log.debug(" %s" % kind)
  2010. self.log.debug(" %s" % filename)
  2011. record = {'kind': str(kind), 'filename': str(filename)}
  2012. if record in self.recent:
  2013. return
  2014. self.recent.insert(0, record)
  2015. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2016. self.recent.pop()
  2017. try:
  2018. f = open(self.data_path + '/recent.json', 'w')
  2019. except IOError:
  2020. App.log.error("Failed to open recent items file for writing.")
  2021. self.inform.emit(_('[ERROR_NOTCL]Failed to open recent files file for writing.'))
  2022. return
  2023. #try:
  2024. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2025. # except:
  2026. # App.log.error("Failed to write to recent items file.")
  2027. # self.inform.emit('ERROR: Failed to write to recent items file.')
  2028. # f.close()
  2029. f.close()
  2030. # Re-buid the recent items menu
  2031. self.setup_recent_items()
  2032. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2033. """
  2034. Creates a new specalized FlatCAMObj and attaches it to the application,
  2035. this is, updates the GUI accordingly, any other records and plots it.
  2036. This method is thread-safe.
  2037. Notes:
  2038. * If the name is in use, the self.collection will modify it
  2039. when appending it to the collection. There is no need to handle
  2040. name conflicts here.
  2041. :param kind: The kind of object to create. One of 'gerber',
  2042. 'excellon', 'cncjob' and 'geometry'.
  2043. :type kind: str
  2044. :param name: Name for the object.
  2045. :type name: str
  2046. :param initialize: Function to run after creation of the object
  2047. but before it is attached to the application. The function is
  2048. called with 2 parameters: the new object and the App instance.
  2049. :type initialize: function
  2050. :return: None
  2051. :rtype: None
  2052. """
  2053. App.log.debug("new_object()")
  2054. obj_plot = plot
  2055. obj_autoselected = autoselected
  2056. t0 = time.time() # Debug
  2057. ## Create object
  2058. classdict = {
  2059. "gerber": FlatCAMGerber,
  2060. "excellon": FlatCAMExcellon,
  2061. "cncjob": FlatCAMCNCjob,
  2062. "geometry": FlatCAMGeometry
  2063. }
  2064. App.log.debug("Calling object constructor...")
  2065. obj = classdict[kind](name)
  2066. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2067. # Set options from "Project options" form
  2068. self.options_read_form()
  2069. # IMPORTANT
  2070. # The key names in defaults and options dictionary's are not random:
  2071. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2072. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2073. # the options from project options form into the self.options. After that, below, depending on the type of
  2074. # object that is created, it will strip the name of the object and the underline (if the original key was
  2075. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2076. # "toolchange"
  2077. for option in self.options:
  2078. if option.find(kind + "_") == 0:
  2079. oname = option[len(kind) + 1:]
  2080. obj.options[oname] = self.options[option]
  2081. obj.isHovering = False
  2082. obj.notHovering = True
  2083. # Initialize as per user request
  2084. # User must take care to implement initialize
  2085. # in a thread-safe way as is is likely that we
  2086. # have been invoked in a separate thread.
  2087. t1 = time.time()
  2088. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2089. try:
  2090. return_value = initialize(obj, self)
  2091. except Exception as e:
  2092. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2093. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2094. msg += traceback.format_exc()
  2095. self.inform.emit(msg)
  2096. # if str(e) == "Empty Geometry":
  2097. # self.inform.emit("[ERROR_NOTCL] )
  2098. # else:
  2099. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2100. return "fail"
  2101. t2 = time.time()
  2102. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2103. if return_value == 'fail':
  2104. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2105. return "fail"
  2106. # Check units and convert if necessary
  2107. # This condition CAN be true because initialize() can change obj.units
  2108. if self.options["units"].upper() != obj.units.upper():
  2109. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2110. obj.convert_units(self.options["units"])
  2111. t3 = time.time()
  2112. self.log.debug("%f seconds converting units." % (t3 - t2))
  2113. # Create the bounding box for the object and then add the results to the obj.options
  2114. try:
  2115. xmin, ymin, xmax, ymax = obj.bounds()
  2116. obj.options['xmin'] = xmin
  2117. obj.options['ymin'] = ymin
  2118. obj.options['xmax'] = xmax
  2119. obj.options['ymax'] = ymax
  2120. except:
  2121. log.warning("The object has no bounds properties.")
  2122. # don't plot objects with no bounds, there is nothing to plot
  2123. self.plot = False
  2124. pass
  2125. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2126. # Move the object to the main thread and let the app know that it is available.
  2127. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  2128. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2129. return obj
  2130. def new_excellon_object(self):
  2131. self.report_usage("new_excellon_object()")
  2132. self.new_object('excellon', 'new_e', lambda x, y: None, plot=False)
  2133. def new_geometry_object(self):
  2134. self.report_usage("new_geometry_object()")
  2135. def initialize(obj, self):
  2136. obj.multitool = False
  2137. self.new_object('geometry', 'new_g', initialize, plot=False)
  2138. def on_object_created(self, obj, plot, autoselect):
  2139. """
  2140. Event callback for object creation.
  2141. :param obj: The newly created FlatCAM object.
  2142. :return: None
  2143. """
  2144. t0 = time.time() # DEBUG
  2145. self.log.debug("on_object_created()")
  2146. # The Collection might change the name if there is a collision
  2147. self.collection.append(obj)
  2148. # after adding the object to the collection always update the list of objects that are in the collection
  2149. self.all_objects_list = self.collection.get_list()
  2150. # self.inform.emit('[selected] %s created & selected: %s' %
  2151. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2152. if obj.kind == 'gerber':
  2153. self.inform.emit(_('[selected]{kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2154. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  2155. elif obj.kind == 'excellon':
  2156. self.inform.emit(_('[selected]{kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2157. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  2158. elif obj.kind == 'cncjob':
  2159. self.inform.emit(_('[selected]{kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2160. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  2161. elif obj.kind == 'geometry':
  2162. self.inform.emit(_('[selected]{kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2163. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  2164. # update the SHELL auto-completer model with the name of the new object
  2165. self.myKeywords.append(obj.options['name'])
  2166. self.shell._edit.set_model_data(self.myKeywords)
  2167. if autoselect:
  2168. # select the just opened object but deselect the previous ones
  2169. self.collection.set_all_inactive()
  2170. self.collection.set_active(obj.options["name"])
  2171. # here it is done the object plotting
  2172. def worker_task(obj):
  2173. with self.proc_container.new("Plotting"):
  2174. if isinstance(obj, FlatCAMCNCjob):
  2175. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2176. else:
  2177. obj.plot()
  2178. t1 = time.time() # DEBUG
  2179. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2180. self.object_plotted.emit(obj)
  2181. # Send to worker
  2182. # self.worker.add_task(worker_task, [self])
  2183. if plot is True:
  2184. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2185. def on_object_changed(self, obj):
  2186. # update the bounding box data from obj.options
  2187. xmin, ymin, xmax, ymax = obj.bounds()
  2188. obj.options['xmin'] = xmin
  2189. obj.options['ymin'] = ymin
  2190. obj.options['xmax'] = xmax
  2191. obj.options['ymax'] = ymax
  2192. log.debug("Object changed, updating the bounding box data on self.options")
  2193. # delete the old selection shape
  2194. self.delete_selection_shape()
  2195. self.should_we_save = True
  2196. def on_object_plotted(self, obj):
  2197. self.on_zoom_fit(None)
  2198. def options_read_form(self):
  2199. for option in self.options_form_fields:
  2200. self.options[option] = self.options_form_fields[option].get_value()
  2201. def options_write_form(self):
  2202. for option in self.options:
  2203. self.options_write_form_field(option)
  2204. def options_write_form_field(self, field):
  2205. try:
  2206. self.options_form_fields[field].set_value(self.options[field])
  2207. except KeyError:
  2208. # Changed from error to debug. This allows to have data stored
  2209. # which is not user-editable.
  2210. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2211. pass
  2212. def on_about(self):
  2213. """
  2214. Displays the "about" dialog.
  2215. :return: None
  2216. """
  2217. self.report_usage("on_about")
  2218. version = self.version
  2219. version_date = self.version_date
  2220. beta = self.beta
  2221. class AboutDialog(QtWidgets.QDialog):
  2222. def __init__(self, parent=None):
  2223. QtWidgets.QDialog.__init__(self, parent)
  2224. # Icon and title
  2225. self.setWindowIcon(parent.app_icon)
  2226. self.setWindowTitle("FlatCAM")
  2227. layout1 = QtWidgets.QVBoxLayout()
  2228. self.setLayout(layout1)
  2229. layout2 = QtWidgets.QHBoxLayout()
  2230. layout1.addLayout(layout2)
  2231. logo = QtWidgets.QLabel()
  2232. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2233. layout2.addWidget(logo, stretch=0)
  2234. title = QtWidgets.QLabel(
  2235. _(
  2236. "<font size=8><B>FlatCAM</B></font><BR>"
  2237. "Version {version} {beta} ({date}) - {arch} <BR>"
  2238. "<BR>"
  2239. "2D Computer-Aided Printed Circuit Board<BR>"
  2240. "Manufacturing.<BR>"
  2241. "<BR>"
  2242. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2243. "<BR>"
  2244. "<B> Main Contributors:</B><BR>"
  2245. "Denis Hayrullin<BR>"
  2246. "Kamil Sopko<BR>"
  2247. "Marius Stanciu<BR>"
  2248. "Matthieu Berthomé<BR>"
  2249. "and many others found "
  2250. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2251. "<BR>"
  2252. "Development is done "
  2253. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2254. "DOWNLOAD area "
  2255. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2256. ""
  2257. ).format(version=version,
  2258. beta=('BETA' if beta else ''),
  2259. date=version_date,
  2260. arch=platform.architecture()[0])
  2261. )
  2262. title.setOpenExternalLinks(True)
  2263. layout2.addWidget(title, stretch=1)
  2264. layout3 = QtWidgets.QHBoxLayout()
  2265. layout1.addLayout(layout3)
  2266. layout3.addStretch()
  2267. okbtn = QtWidgets.QPushButton("Close")
  2268. layout3.addWidget(okbtn)
  2269. okbtn.clicked.connect(self.accept)
  2270. AboutDialog(self.ui).exec_()
  2271. def on_file_savedefaults(self):
  2272. """
  2273. Callback for menu item File->Save Defaults. Saves application default options
  2274. ``self.defaults`` to current_defaults.FlatConfig.
  2275. :return: None
  2276. """
  2277. self.save_defaults()
  2278. def on_app_exit(self):
  2279. self.report_usage("on_app_exit()")
  2280. if self.collection.get_list():
  2281. msgbox = QtWidgets.QMessageBox()
  2282. # msgbox.setText("<B>Save changes ...</B>")
  2283. msgbox.setText("There are files/objects opened in FlatCAM. "
  2284. "\n"
  2285. "Do you want to Save the project?")
  2286. msgbox.setWindowTitle("Save changes")
  2287. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2288. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2289. QtWidgets.QMessageBox.Cancel)
  2290. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2291. response = msgbox.exec_()
  2292. if response == QtWidgets.QMessageBox.Yes:
  2293. self.on_file_saveprojectas(thread=False)
  2294. elif response == QtWidgets.QMessageBox.Cancel:
  2295. return
  2296. self.save_defaults()
  2297. else:
  2298. self.save_defaults()
  2299. log.debug("Application defaults saved ... Exit event.")
  2300. QtWidgets.qApp.quit()
  2301. def save_defaults(self, silent=False):
  2302. """
  2303. Saves application default options
  2304. ``self.defaults`` to current_defaults.FlatConfig.
  2305. :return: None
  2306. """
  2307. self.report_usage("save_defaults")
  2308. # Read options from file
  2309. try:
  2310. f = open(self.data_path + "/current_defaults.FlatConfig")
  2311. defaults_file_content = f.read()
  2312. f.close()
  2313. except:
  2314. e = sys.exc_info()[0]
  2315. App.log.error("Could not load defaults file.")
  2316. App.log.error(str(e))
  2317. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2318. return
  2319. try:
  2320. defaults = json.loads(defaults_file_content)
  2321. except:
  2322. e = sys.exc_info()[0]
  2323. App.log.error("Failed to parse defaults file.")
  2324. App.log.error(str(e))
  2325. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2326. return
  2327. # Update options
  2328. self.defaults_read_form()
  2329. defaults.update(self.defaults)
  2330. self.propagate_defaults(silent=True)
  2331. # Save update options
  2332. try:
  2333. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2334. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  2335. f.close()
  2336. except:
  2337. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2338. return
  2339. # Save the toolbar view
  2340. tb_status = 0
  2341. if self.ui.toolbarfile.isVisible():
  2342. tb_status += 1
  2343. if self.ui.toolbargeo.isVisible():
  2344. tb_status += 2
  2345. if self.ui.toolbarview.isVisible():
  2346. tb_status += 4
  2347. if self.ui.toolbartools.isVisible():
  2348. tb_status += 8
  2349. if self.ui.exc_edit_toolbar.isVisible():
  2350. tb_status += 16
  2351. if self.ui.geo_edit_toolbar.isVisible():
  2352. tb_status += 32
  2353. if self.ui.snap_toolbar.isVisible():
  2354. tb_status += 64
  2355. if self.ui.toolbarshell.isVisible():
  2356. tb_status += 128
  2357. self.defaults["global_toolbar_view"] = tb_status
  2358. if not silent:
  2359. self.inform.emit(_("[success]Defaults saved."))
  2360. def save_factory_defaults(self, silent=False):
  2361. """
  2362. Saves application factory default options
  2363. ``self.defaults`` to factory_defaults.FlatConfig.
  2364. It's a one time job done just after the first install.
  2365. :return: None
  2366. """
  2367. self.report_usage("save_factory_defaults")
  2368. # Read options from file
  2369. try:
  2370. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2371. factory_defaults_file_content = f_f_def.read()
  2372. f_f_def.close()
  2373. except:
  2374. e = sys.exc_info()[0]
  2375. App.log.error("Could not load factory defaults file.")
  2376. App.log.error(str(e))
  2377. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  2378. return
  2379. try:
  2380. factory_defaults = json.loads(factory_defaults_file_content)
  2381. except:
  2382. e = sys.exc_info()[0]
  2383. App.log.error("Failed to parse factory defaults file.")
  2384. App.log.error(str(e))
  2385. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  2386. return
  2387. # Update options
  2388. self.defaults_read_form()
  2389. factory_defaults.update(self.defaults)
  2390. self.propagate_defaults(silent=True)
  2391. # Save update options
  2392. try:
  2393. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2394. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  2395. f_f_def_s.close()
  2396. except:
  2397. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  2398. return
  2399. if silent is False:
  2400. self.inform.emit(_("Factory defaults saved."))
  2401. def final_save(self):
  2402. if self.should_we_save and self.collection.get_list():
  2403. msgbox = QtWidgets.QMessageBox()
  2404. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2405. "\n"
  2406. "Do you want to Save the project?"))
  2407. msgbox.setWindowTitle(_("Save changes"))
  2408. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2409. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2410. QtWidgets.QMessageBox.Cancel)
  2411. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2412. response = msgbox.exec_()
  2413. if response == QtWidgets.QMessageBox.Yes:
  2414. self.on_file_saveprojectas(thread=False)
  2415. elif response == QtWidgets.QMessageBox.Cancel:
  2416. self.should_we_quit = False
  2417. return
  2418. self.save_defaults()
  2419. log.debug("App.final_save() --> App Defaults saved.")
  2420. # save toolbar state to file
  2421. settings = QSettings("Open Source", "FlatCAM")
  2422. settings.setValue('saved_gui_state', self.ui.saveState())
  2423. settings.setValue('maximized_gui', self.ui.isMaximized())
  2424. # This will write the setting to the platform specific storage.
  2425. del settings
  2426. log.debug("App.final_save() --> App UI state saved.")
  2427. QtWidgets.qApp.quit()
  2428. def on_toggle_shell(self):
  2429. """
  2430. toggle shell if is visible close it if closed open it
  2431. :return:
  2432. """
  2433. self.report_usage("on_toggle_shell()")
  2434. if self.ui.shell_dock.isVisible():
  2435. self.ui.shell_dock.hide()
  2436. else:
  2437. self.ui.shell_dock.show()
  2438. def on_edit_join(self, name=None):
  2439. """
  2440. Callback for Edit->Join. Joins the selected geometry objects into
  2441. a new one.
  2442. :return: None
  2443. """
  2444. self.report_usage("on_edit_join()")
  2445. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2446. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2447. tooldias = []
  2448. geo_type_list = []
  2449. objs = self.collection.get_selected()
  2450. for obj in objs:
  2451. geo_type_list.append(obj.multigeo)
  2452. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2453. if len(set(geo_type_list)) != 1:
  2454. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2455. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2456. "convert from one to another and retry joining \n"
  2457. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2458. "the result may not be what was expected. \n"
  2459. "Check the generated GCODE."))
  2460. return
  2461. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2462. if True in geo_type_list:
  2463. def initialize(obj, app):
  2464. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2465. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2466. for v in obj.tools.values():
  2467. v['data']['name'] = obj_name_multi
  2468. self.new_object("geometry", obj_name_multi, initialize)
  2469. else:
  2470. def initialize(obj, app):
  2471. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2472. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2473. for v in obj.tools.values():
  2474. v['data']['name'] = obj_name_single
  2475. self.new_object("geometry", obj_name_single, initialize)
  2476. self.should_we_save = True
  2477. def on_edit_join_exc(self):
  2478. """
  2479. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2480. a new one.
  2481. :return: None
  2482. """
  2483. self.report_usage("on_edit_join_exc()")
  2484. objs = self.collection.get_selected()
  2485. for obj in objs:
  2486. if not isinstance(obj, FlatCAMExcellon):
  2487. self.inform.emit(_("[ERROR_NOTCL]Failed. Excellon joining works only on Excellon objects."))
  2488. return
  2489. def initialize(obj, app):
  2490. FlatCAMExcellon.merge(objs, obj)
  2491. self.new_object("excellon", 'Combo_Excellon', initialize)
  2492. self.should_we_save = True
  2493. def on_edit_join_grb(self):
  2494. """
  2495. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2496. a new one.
  2497. :return: None
  2498. """
  2499. self.report_usage("on_edit_join_grb()")
  2500. objs = self.collection.get_selected()
  2501. for obj in objs:
  2502. if not isinstance(obj, FlatCAMGerber):
  2503. self.inform.emit(_("[ERROR_NOTCL]Failed. Gerber joining works only on Gerber objects."))
  2504. return
  2505. def initialize(obj, app):
  2506. FlatCAMGerber.merge(objs, obj)
  2507. self.new_object("gerber", 'Combo_Gerber', initialize)
  2508. self.should_we_save = True
  2509. def on_convert_singlegeo_to_multigeo(self):
  2510. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2511. obj = self.collection.get_active()
  2512. if obj is None:
  2513. self.inform.emit(_("[ERROR_NOTCL]Failed. Select a Geometry Object and try again."))
  2514. return
  2515. if not isinstance(obj, FlatCAMGeometry):
  2516. self.inform.emit(_("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s") % type(obj))
  2517. return
  2518. obj.multigeo = True
  2519. for tooluid, dict_value in obj.tools.items():
  2520. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2521. if not isinstance(obj.solid_geometry, list):
  2522. obj.solid_geometry = [obj.solid_geometry]
  2523. obj.solid_geometry[:] = []
  2524. obj.plot()
  2525. self.should_we_save = True
  2526. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  2527. def on_convert_multigeo_to_singlegeo(self):
  2528. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2529. obj = self.collection.get_active()
  2530. if obj is None:
  2531. self.inform.emit(_("[ERROR_NOTCL]Failed. Select a Geometry Object and try again."))
  2532. return
  2533. if not isinstance(obj, FlatCAMGeometry):
  2534. self.inform.emit(_("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s") % type(obj))
  2535. return
  2536. obj.multigeo = False
  2537. total_solid_geometry = []
  2538. for tooluid, dict_value in obj.tools.items():
  2539. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2540. # clear the original geometry
  2541. dict_value['solid_geometry'][:] = []
  2542. obj.solid_geometry = deepcopy(total_solid_geometry)
  2543. obj.plot()
  2544. self.should_we_save = True
  2545. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  2546. def on_options_dict_change(self, field):
  2547. self.options_write_form_field(field)
  2548. if field == "units":
  2549. self.set_screen_units(self.options['units'])
  2550. def on_defaults_dict_change(self, field):
  2551. self.defaults_write_form_field(field)
  2552. if field == "units":
  2553. self.set_screen_units(self.defaults['units'])
  2554. def set_screen_units(self, units):
  2555. self.ui.units_label.setText("[" + self.defaults["units"].lower() + "]")
  2556. def on_toggle_units(self):
  2557. """
  2558. Callback for the Units radio-button change in the Options tab.
  2559. Changes the application's default units or the current project's units.
  2560. If changing the project's units, the change propagates to all of
  2561. the objects in the project.
  2562. :return: None
  2563. """
  2564. self.report_usage("on_toggle_units")
  2565. if self.toggle_units_ignore:
  2566. return
  2567. # If option is the same, then ignore
  2568. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == \
  2569. self.defaults["units"].upper():
  2570. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  2571. return
  2572. # Options to scale
  2573. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  2574. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  2575. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2576. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  2577. "excellon_z_pdepth",
  2578. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  2579. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  2580. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  2581. "geometry_feedrate_probe",
  2582. 'cncjob_tooldia',
  2583. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  2584. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin",
  2585. "tools_2sided_drilldia", "tools_film_boundary",
  2586. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2587. "tools_panelize_constrainx", "tools_panelize_constrainy",
  2588. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  2589. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  2590. "tools_transform_offset_y",
  2591. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  2592. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  2593. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  2594. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  2595. 'global_gridx', 'global_gridy', 'global_snap_max']
  2596. def scale_options(sfactor):
  2597. for dim in dimensions:
  2598. if dim == 'excellon_toolchangexy':
  2599. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2600. coords_xy[0] *= sfactor
  2601. coords_xy[1] *= sfactor
  2602. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2603. elif dim == 'geometry_toolchangexy':
  2604. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2605. coords_xy[0] *= sfactor
  2606. coords_xy[1] *= sfactor
  2607. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2608. elif dim == 'tools_ncctools':
  2609. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  2610. ncctols[0] *= sfactor
  2611. ncctols[1] *= sfactor
  2612. self.options['tools_ncctools'] = "%f, %f" % (ncctols[0], ncctols[1])
  2613. elif dim == 'tools_solderpaste_tools':
  2614. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  2615. sp_tools[0] *= sfactor
  2616. sp_tools[1] *= sfactor
  2617. self.options['tools_solderpaste_tools'] = "%f, %f" % (sp_tools[0], sp_tools[1])
  2618. elif dim == 'tools_solderpaste_xy_toolchange':
  2619. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  2620. sp_coords[0] *= sfactor
  2621. sp_coords[1] *= sfactor
  2622. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  2623. else:
  2624. try:
  2625. self.options[dim] = float(self.options[dim]) * sfactor
  2626. except Exception as e:
  2627. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  2628. def scale_defaults(sfactor):
  2629. for dim in dimensions:
  2630. if dim == 'excellon_toolchangexy':
  2631. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2632. coords_xy[0] *= sfactor
  2633. coords_xy[1] *= sfactor
  2634. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  2635. elif dim == 'geometry_toolchangexy':
  2636. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2637. coords_xy[0] *= sfactor
  2638. coords_xy[1] *= sfactor
  2639. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  2640. elif dim == 'tools_ncctools':
  2641. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  2642. ncctols[0] *= sfactor
  2643. ncctols[1] *= sfactor
  2644. self.defaults['tools_ncctools'] = "%.4f, %.4f" % (ncctols[0], ncctols[1])
  2645. elif dim == 'tools_solderpaste_tools':
  2646. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  2647. sp_tools[0] *= sfactor
  2648. sp_tools[1] *= sfactor
  2649. self.defaults['tools_solderpaste_tools'] = "%.4f, %.4f" % (sp_tools[0], sp_tools[1])
  2650. elif dim == 'tools_solderpaste_xy_toolchange':
  2651. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  2652. sp_coords[0] *= sfactor
  2653. sp_coords[1] *= sfactor
  2654. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  2655. else:
  2656. try:
  2657. self.defaults[dim] = float(self.defaults[dim]) * sfactor
  2658. except Exception as e:
  2659. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  2660. # The scaling factor depending on choice of units.
  2661. factor = 1/25.4
  2662. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2663. factor = 25.4
  2664. # Changing project units. Warn user.
  2665. msgbox = QtWidgets.QMessageBox()
  2666. msgbox.setText("<B>Change project units ...</B>")
  2667. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2668. "properties of all objects to be scaled accordingly. Continue?")
  2669. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2670. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2671. response = msgbox.exec_()
  2672. if response == QtWidgets.QMessageBox.Ok:
  2673. self.options_read_form()
  2674. scale_options(factor)
  2675. self.options_write_form()
  2676. self.defaults_read_form()
  2677. scale_defaults(factor)
  2678. self.defaults_write_form()
  2679. self.should_we_save = True
  2680. # change this only if the workspace is active
  2681. if self.defaults['global_workspace'] is True:
  2682. self.plotcanvas.draw_workspace()
  2683. # adjust the grid values on the main toolbar
  2684. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2685. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2686. for obj in self.collection.get_list():
  2687. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  2688. obj.convert_units(units)
  2689. # make that the properties stored in the object are also updated
  2690. self.object_changed.emit(obj)
  2691. obj.build_ui()
  2692. current = self.collection.get_active()
  2693. if current is not None:
  2694. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2695. if not isinstance(current, FlatCAMGeometry):
  2696. current.to_form()
  2697. self.plot_all()
  2698. self.inform.emit(_("[success]Converted units to %s") % self.defaults["units"])
  2699. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  2700. self.set_screen_units(self.defaults["units"])
  2701. else:
  2702. # Undo toggling
  2703. self.toggle_units_ignore = True
  2704. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2705. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  2706. else:
  2707. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  2708. self.toggle_units_ignore = False
  2709. self.inform.emit(_("[WARNING_NOTCL]Units conversion cancelled."))
  2710. self.options_read_form()
  2711. self.defaults_read_form()
  2712. def on_toggle_units_click(self):
  2713. if self.options["units"] == 'MM':
  2714. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  2715. else:
  2716. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  2717. self.on_toggle_units()
  2718. def on_fullscreen(self):
  2719. self.report_usage("on_fullscreen()")
  2720. if self.toggle_fscreen is False:
  2721. if sys.platform == 'win32':
  2722. self.ui.showFullScreen()
  2723. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2724. tb.setVisible(False)
  2725. self.ui.splitter_left.setVisible(False)
  2726. self.toggle_fscreen = True
  2727. else:
  2728. if sys.platform == 'win32':
  2729. self.ui.showNormal()
  2730. self.restore_toolbar_view()
  2731. self.ui.splitter_left.setVisible(True)
  2732. self.toggle_fscreen = False
  2733. def on_toggle_plotarea(self):
  2734. self.report_usage("on_toggle_plotarea()")
  2735. try:
  2736. name = self.ui.plot_tab_area.widget(0).objectName()
  2737. except AttributeError:
  2738. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  2739. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2740. self.ui.plot_tab_area.protectTab(0)
  2741. return
  2742. if name != 'plotarea':
  2743. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  2744. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2745. self.ui.plot_tab_area.protectTab(0)
  2746. else:
  2747. self.ui.plot_tab_area.closeTab(0)
  2748. def on_toggle_notebook(self):
  2749. if self.ui.splitter.sizes()[0] == 0:
  2750. self.ui.splitter.setSizes([1, 1])
  2751. else:
  2752. self.ui.splitter.setSizes([0, 1])
  2753. def on_toggle_axis(self):
  2754. self.report_usage("on_toggle_axis()")
  2755. if self.toggle_axis is False:
  2756. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2757. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2758. self.plotcanvas.redraw()
  2759. self.toggle_axis = True
  2760. else:
  2761. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2762. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2763. self.plotcanvas.redraw()
  2764. self.toggle_axis = False
  2765. def on_toggle_grid(self):
  2766. self.report_usage("on_toggle_grid()")
  2767. self.ui.grid_snap_btn.trigger()
  2768. def on_options_combo_change(self, sel):
  2769. """
  2770. Called when the combo box to choose between application defaults and
  2771. project option changes value. The corresponding variables are
  2772. copied to the UI.
  2773. :param sel: The option index that was chosen.
  2774. :return: None
  2775. """
  2776. # combo_sel = self.ui.notebook.combo_options.get_active()
  2777. App.log.debug("Options --> %s" % sel)
  2778. # form = [self.defaults_form, self.options_form][sel]
  2779. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2780. if sel == 0:
  2781. self.gen_form = self.ui.general_defaults_form
  2782. self.ger_form = self.ui.gerber_defaults_form
  2783. self.exc_form = self.ui.excellon_defaults_form
  2784. self.geo_form = self.ui.geometry_defaults_form
  2785. self.cnc_form = self.ui.cncjob_defaults_form
  2786. self.tools_form = self.ui.tools_defaults_form
  2787. elif sel == 1:
  2788. self.gen_form = self.ui.general_options_form
  2789. self.ger_form = self.ui.gerber_options_form
  2790. self.exc_form = self.ui.excellon_options_form
  2791. self.geo_form = self.ui.geometry_options_form
  2792. self.cnc_form = self.ui.cncjob_options_form
  2793. self.tools_form = self.ui.tools_options_form
  2794. else:
  2795. return
  2796. try:
  2797. self.ui.general_scroll_area.takeWidget()
  2798. except:
  2799. self.log.debug("Nothing to remove")
  2800. self.ui.general_scroll_area.setWidget(self.gen_form)
  2801. self.gen_form.show()
  2802. try:
  2803. self.ui.gerber_scroll_area.takeWidget()
  2804. except:
  2805. self.log.debug("Nothing to remove")
  2806. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2807. self.ger_form.show()
  2808. try:
  2809. self.ui.excellon_scroll_area.takeWidget()
  2810. except:
  2811. self.log.debug("Nothing to remove")
  2812. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2813. self.exc_form.show()
  2814. try:
  2815. self.ui.geometry_scroll_area.takeWidget()
  2816. except:
  2817. self.log.debug("Nothing to remove")
  2818. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2819. self.geo_form.show()
  2820. try:
  2821. self.ui.cncjob_scroll_area.takeWidget()
  2822. except:
  2823. self.log.debug("Nothing to remove")
  2824. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2825. self.cnc_form.show()
  2826. try:
  2827. self.ui.tools_scroll_area.takeWidget()
  2828. except:
  2829. self.log.debug("Nothing to remove")
  2830. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2831. self.tools_form.show()
  2832. self.log.debug("Finished GUI form initialization.")
  2833. # self.options2form()
  2834. def on_excellon_defaults_button(self):
  2835. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2836. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2837. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2838. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2839. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2840. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2841. log.debug("Excellon app defaults loaded ...")
  2842. def on_excellon_options_button(self):
  2843. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2844. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2845. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2846. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2847. self.options_form_fields["excellon_zeros"].set_value('L')
  2848. self.options_form_fields["excellon_units"].set_value('INCH')
  2849. log.debug("Excellon options defaults loaded ...")
  2850. # Setting plot colors handlers
  2851. def on_pf_color_entry(self):
  2852. self.defaults['global_plot_fill'] = self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2853. self.defaults['global_plot_fill'][7:9]
  2854. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2855. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2856. def on_pf_color_button(self):
  2857. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2858. c_dialog = QtWidgets.QColorDialog()
  2859. plot_fill_color = c_dialog.getColor(initial=current_color)
  2860. if plot_fill_color.isValid() is False:
  2861. return
  2862. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2863. "background-color:%s" % str(plot_fill_color.name()))
  2864. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2865. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2866. self.defaults['global_plot_fill'] = new_val
  2867. def on_pf_color_spinner(self):
  2868. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2869. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2870. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2871. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2872. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2873. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2874. def on_pf_color_slider(self):
  2875. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2876. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2877. def on_pl_color_entry(self):
  2878. self.defaults['global_plot_line'] = self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2879. self.defaults['global_plot_line'][7:9]
  2880. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2881. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2882. def on_pl_color_button(self):
  2883. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2884. # print(current_color)
  2885. c_dialog = QtWidgets.QColorDialog()
  2886. plot_line_color = c_dialog.getColor(initial=current_color)
  2887. if plot_line_color.isValid() is False:
  2888. return
  2889. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2890. "background-color:%s" % str(plot_line_color.name()))
  2891. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2892. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2893. self.defaults['global_plot_line'] = new_val_line
  2894. # Setting selection colors (left - right) handlers
  2895. def on_sf_color_entry(self):
  2896. self.defaults['global_sel_fill'] = self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2897. self.defaults['global_sel_fill'][7:9]
  2898. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2899. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2900. def on_sf_color_button(self):
  2901. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2902. c_dialog = QtWidgets.QColorDialog()
  2903. plot_fill_color = c_dialog.getColor(initial=current_color)
  2904. if plot_fill_color.isValid() is False:
  2905. return
  2906. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2907. "background-color:%s" % str(plot_fill_color.name()))
  2908. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2909. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2910. self.defaults['global_sel_fill'] = new_val
  2911. def on_sf_color_spinner(self):
  2912. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2913. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2914. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2915. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2916. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2917. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2918. def on_sf_color_slider(self):
  2919. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2920. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2921. def on_sl_color_entry(self):
  2922. self.defaults['global_sel_line'] = self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2923. self.defaults['global_sel_line'][7:9]
  2924. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2925. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2926. def on_sl_color_button(self):
  2927. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2928. c_dialog = QtWidgets.QColorDialog()
  2929. plot_line_color = c_dialog.getColor(initial=current_color)
  2930. if plot_line_color.isValid() is False:
  2931. return
  2932. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2933. "background-color:%s" % str(plot_line_color.name()))
  2934. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2935. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2936. self.defaults['global_sel_line'] = new_val_line
  2937. # Setting selection colors (right - left) handlers
  2938. def on_alt_sf_color_entry(self):
  2939. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  2940. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2941. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2942. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2943. def on_alt_sf_color_button(self):
  2944. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2945. c_dialog = QtWidgets.QColorDialog()
  2946. plot_fill_color = c_dialog.getColor(initial=current_color)
  2947. if plot_fill_color.isValid() is False:
  2948. return
  2949. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2950. "background-color:%s" % str(plot_fill_color.name()))
  2951. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2952. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2953. self.defaults['global_alt_sel_fill'] = new_val
  2954. def on_alt_sf_color_spinner(self):
  2955. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2956. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2957. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2958. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2959. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2960. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2961. def on_alt_sf_color_slider(self):
  2962. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2963. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2964. def on_alt_sl_color_entry(self):
  2965. self.defaults['global_alt_sel_line'] = self.ui.general_defaults_form.general_gui_group \
  2966. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2967. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2968. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2969. def on_alt_sl_color_button(self):
  2970. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2971. c_dialog = QtWidgets.QColorDialog()
  2972. plot_line_color = c_dialog.getColor(initial=current_color)
  2973. if plot_line_color.isValid() is False:
  2974. return
  2975. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2976. "background-color:%s" % str(plot_line_color.name()))
  2977. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2978. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2979. self.defaults['global_alt_sel_line'] = new_val_line
  2980. # Setting Editor colors
  2981. def on_draw_color_entry(self):
  2982. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  2983. .draw_color_entry.get_value()
  2984. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2985. "background-color:%s" % str(self.defaults['global_draw_color']))
  2986. def on_draw_color_button(self):
  2987. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2988. c_dialog = QtWidgets.QColorDialog()
  2989. draw_color = c_dialog.getColor(initial=current_color)
  2990. if draw_color.isValid() is False:
  2991. return
  2992. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2993. "background-color:%s" % str(draw_color.name()))
  2994. new_val = str(draw_color.name())
  2995. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  2996. self.defaults['global_draw_color'] = new_val
  2997. def on_sel_draw_color_entry(self):
  2998. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  2999. .sel_draw_color_entry.get_value()
  3000. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3001. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  3002. def on_sel_draw_color_button(self):
  3003. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  3004. c_dialog = QtWidgets.QColorDialog()
  3005. sel_draw_color = c_dialog.getColor(initial=current_color)
  3006. if sel_draw_color.isValid() is False:
  3007. return
  3008. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3009. "background-color:%s" % str(sel_draw_color.name()))
  3010. new_val_sel = str(sel_draw_color.name())
  3011. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  3012. self.defaults['global_sel_draw_color'] = new_val_sel
  3013. def on_deselect_all(self):
  3014. self.collection.set_all_inactive()
  3015. self.delete_selection_shape()
  3016. def on_workspace_modified(self):
  3017. self.save_defaults(silent=True)
  3018. self.plotcanvas.draw_workspace()
  3019. def on_workspace(self):
  3020. self.report_usage("on_workspace()")
  3021. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3022. self.plotcanvas.restore_workspace()
  3023. else:
  3024. self.plotcanvas.delete_workspace()
  3025. self.save_defaults(silent=True)
  3026. def on_workspace_menu(self):
  3027. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3028. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  3029. else:
  3030. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  3031. self.on_workspace()
  3032. def on_layout(self, index, lay=None):
  3033. self.report_usage("on_layout()")
  3034. if lay:
  3035. current_layout = lay
  3036. else:
  3037. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  3038. settings = QSettings("Open Source", "FlatCAM")
  3039. settings.setValue('layout', current_layout)
  3040. # This will write the setting to the platform specific storage.
  3041. del settings
  3042. # first remove the toolbars:
  3043. try:
  3044. self.ui.removeToolBar(self.ui.toolbarfile)
  3045. self.ui.removeToolBar(self.ui.toolbargeo)
  3046. self.ui.removeToolBar(self.ui.toolbarview)
  3047. self.ui.removeToolBar(self.ui.toolbarshell)
  3048. self.ui.removeToolBar(self.ui.toolbartools)
  3049. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  3050. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  3051. self.ui.removeToolBar(self.ui.snap_toolbar)
  3052. self.ui.removeToolBar(self.ui.toolbarshell)
  3053. except:
  3054. pass
  3055. if current_layout == 'Standard':
  3056. ### TOOLBAR INSTALLATION ###
  3057. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3058. self.ui.toolbarfile.setObjectName('File_TB')
  3059. self.ui.addToolBar(self.ui.toolbarfile)
  3060. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3061. self.ui.toolbargeo.setObjectName('Edit_TB')
  3062. self.ui.addToolBar(self.ui.toolbargeo)
  3063. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3064. self.ui.toolbarview.setObjectName('View_TB')
  3065. self.ui.addToolBar(self.ui.toolbarview)
  3066. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3067. self.ui.toolbarshell.setObjectName('Shell_TB')
  3068. self.ui.addToolBar(self.ui.toolbarshell)
  3069. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3070. self.ui.toolbartools.setObjectName('Tools_TB')
  3071. self.ui.addToolBar(self.ui.toolbartools)
  3072. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3073. self.ui.exc_edit_toolbar.setVisible(False)
  3074. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3075. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  3076. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3077. self.ui.geo_edit_toolbar.setVisible(False)
  3078. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3079. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  3080. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3081. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3082. # self.ui.snap_toolbar.setMaximumHeight(30)
  3083. self.ui.addToolBar(self.ui.snap_toolbar)
  3084. self.ui.corner_snap_btn.setVisible(False)
  3085. self.ui.snap_magnet.setVisible(False)
  3086. elif current_layout == 'Compact':
  3087. ### TOOLBAR INSTALLATION ###
  3088. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3089. self.ui.toolbarfile.setObjectName('File_TB')
  3090. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  3091. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3092. self.ui.toolbargeo.setObjectName('Edit_TB')
  3093. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  3094. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3095. self.ui.toolbarview.setObjectName('View_TB')
  3096. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  3097. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3098. self.ui.toolbarshell.setObjectName('Shell_TB')
  3099. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  3100. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3101. self.ui.toolbartools.setObjectName('Tools_TB')
  3102. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  3103. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3104. # self.ui.geo_edit_toolbar.setVisible(False)
  3105. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3106. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  3107. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3108. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3109. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  3110. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3111. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3112. self.ui.snap_toolbar.setMaximumHeight(30)
  3113. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  3114. self.ui.corner_snap_btn.setVisible(True)
  3115. self.ui.snap_magnet.setVisible(True)
  3116. # add all the actions to the toolbars
  3117. self.ui.populate_toolbars()
  3118. # reconnect all the signals to the toolbar actions
  3119. self.connect_toolbar_signals()
  3120. self.ui.grid_snap_btn.setChecked(True)
  3121. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  3122. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  3123. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  3124. self.ui.grid_gap_link_cb.setChecked(True)
  3125. def on_cnc_custom_parameters(self, signal_text):
  3126. if signal_text == 'Parameters':
  3127. return
  3128. else:
  3129. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  3130. def on_save_button(self):
  3131. self.save_defaults(silent=False)
  3132. # load the defaults so they are updated into the app
  3133. self.load_defaults(filename='current_defaults')
  3134. # Re-fresh project options
  3135. self.on_options_app2project()
  3136. def handlePrint(self):
  3137. self.report_usage("handlePrint()")
  3138. dialog = QtPrintSupport.QPrintDialog()
  3139. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  3140. self.ui.code_editor.document().print_(dialog.printer())
  3141. def handlePreview(self):
  3142. self.report_usage("handlePreview()")
  3143. dialog = QtPrintSupport.QPrintPreviewDialog()
  3144. dialog.paintRequested.connect(self.ui.code_editor.print_)
  3145. dialog.exec_()
  3146. def handleTextChanged(self):
  3147. self.report_usage("handleTextChanged()")
  3148. # enable = not self.ui.code_editor.document().isEmpty()
  3149. # self.ui.buttonPrint.setEnabled(enable)
  3150. # self.ui.buttonPreview.setEnabled(enable)
  3151. pass
  3152. def handleOpen(self, filt=None):
  3153. self.report_usage("handleOpen()")
  3154. if filt:
  3155. _filter_ = filt
  3156. else:
  3157. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3158. "All Files (*.*)"
  3159. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  3160. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  3161. if path:
  3162. file = QtCore.QFile(path)
  3163. if file.open(QtCore.QIODevice.ReadOnly):
  3164. stream = QtCore.QTextStream(file)
  3165. self.gcode_edited = stream.readAll()
  3166. self.ui.code_editor.setPlainText(self.gcode_edited)
  3167. file.close()
  3168. def handleSaveGCode(self,name=None, filt=None):
  3169. self.report_usage("handleSaveGCode()")
  3170. if filt:
  3171. _filter_ = filt
  3172. else:
  3173. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3174. "All Files (*.*)"
  3175. if name:
  3176. obj_name = name
  3177. else:
  3178. try:
  3179. obj_name = self.collection.get_active().options['name']
  3180. except AttributeError:
  3181. obj_name = 'file'
  3182. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  3183. try:
  3184. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3185. caption=_("Export G-Code ..."),
  3186. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  3187. filter=_filter_
  3188. )[0])
  3189. except TypeError:
  3190. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  3191. if filename == "":
  3192. self.inform.emit(_("[WARNING_NOTCL]Export Code cancelled."))
  3193. return
  3194. else:
  3195. try:
  3196. my_gcode = self.ui.code_editor.toPlainText()
  3197. with open(filename, 'w') as f:
  3198. for line in my_gcode:
  3199. f.write(line)
  3200. except FileNotFoundError:
  3201. self.inform.emit(_("[WARNING] No such file or directory"))
  3202. return
  3203. # Just for adding it to the recent files list.
  3204. self.file_opened.emit("cncjob", filename)
  3205. self.file_saved.emit("cncjob", filename)
  3206. self.inform.emit(_("Saved to: %s") % filename)
  3207. def handleFindGCode(self):
  3208. self.report_usage("handleFindGCode()")
  3209. flags = QtGui.QTextDocument.FindCaseSensitively
  3210. text_to_be_found = self.ui.entryFind.get_value()
  3211. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  3212. if r is False:
  3213. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3214. def handleReplaceGCode(self):
  3215. self.report_usage("handleReplaceGCode()")
  3216. old = self.ui.entryFind.get_value()
  3217. new = self.ui.entryReplace.get_value()
  3218. if self.ui.sel_all_cb.isChecked():
  3219. while True:
  3220. cursor = self.ui.code_editor.textCursor()
  3221. cursor.beginEditBlock()
  3222. flags = QtGui.QTextDocument.FindCaseSensitively
  3223. # self.ui.editor is the QPlainTextEdit
  3224. r = self.ui.code_editor.find(str(old), flags)
  3225. if r:
  3226. qc = self.ui.code_editor.textCursor()
  3227. if qc.hasSelection():
  3228. qc.insertText(new)
  3229. else:
  3230. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3231. break
  3232. # Mark end of undo block
  3233. cursor.endEditBlock()
  3234. else:
  3235. cursor = self.ui.code_editor.textCursor()
  3236. cursor.beginEditBlock()
  3237. qc = self.ui.code_editor.textCursor()
  3238. if qc.hasSelection():
  3239. qc.insertText(new)
  3240. # Mark end of undo block
  3241. cursor.endEditBlock()
  3242. def on_tool_add_keypress(self):
  3243. ## Current application units in Upper Case
  3244. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3245. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3246. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3247. if notebook_widget_name == 'selected_tab':
  3248. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3249. # Tool add works for Geometry only if Advanced is True in Preferences
  3250. if self.defaults["global_app_level"] == 'a':
  3251. tool_add_popup = FCInputDialog(title="New Tool ...",
  3252. text='Enter a Tool Diameter:',
  3253. min=0.0000, max=99.9999, decimals=4)
  3254. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3255. val, ok = tool_add_popup.get_value()
  3256. if ok:
  3257. if float(val) == 0:
  3258. self.inform.emit(
  3259. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3260. return
  3261. self.collection.get_active().on_tool_add(dia=float(val))
  3262. else:
  3263. self.inform.emit(
  3264. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3265. else:
  3266. msgbox = QtWidgets.QMessageBox()
  3267. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3268. "Go to Preferences -> General - Show Advanced Options."))
  3269. msgbox.setWindowTitle("Tool adding ...")
  3270. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  3271. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3272. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3273. msgbox.exec_()
  3274. # work only if the notebook tab on focus is the Tools_Tab
  3275. if notebook_widget_name == 'tool_tab':
  3276. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3277. tool_add_popup = FCInputDialog(title="New Tool ...",
  3278. text='Enter a Tool Diameter:',
  3279. min=0.0000, max=99.9999, decimals=4)
  3280. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3281. val, ok = tool_add_popup.get_value()
  3282. # and only if the tool is NCC Tool
  3283. if tool_widget == self.ncclear_tool.toolName:
  3284. if ok:
  3285. if float(val) == 0:
  3286. self.inform.emit(
  3287. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3288. return
  3289. self.ncclear_tool.on_tool_add(dia=float(val))
  3290. else:
  3291. self.inform.emit(
  3292. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3293. # and only if the tool is Paint Area Tool
  3294. elif tool_widget == self.paint_tool.toolName:
  3295. if ok:
  3296. if float(val) == 0:
  3297. self.inform.emit(
  3298. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3299. return
  3300. self.paint_tool.on_tool_add(dia=float(val))
  3301. else:
  3302. self.inform.emit(
  3303. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3304. # and only if the tool is Solder Paste Dispensing Tool
  3305. elif tool_widget == self.paste_tool.toolName:
  3306. if ok:
  3307. if float(val) == 0:
  3308. self.inform.emit(
  3309. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3310. return
  3311. self.paste_tool.on_tool_add(dia=float(val))
  3312. else:
  3313. self.inform.emit(
  3314. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3315. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3316. # See description bellow.
  3317. def on_delete_keypress(self):
  3318. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3319. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3320. if notebook_widget_name == 'selected_tab':
  3321. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3322. self.collection.get_active().on_tool_delete()
  3323. # work only if the notebook tab on focus is the Tools_Tab
  3324. elif notebook_widget_name == 'tool_tab':
  3325. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3326. # and only if the tool is NCC Tool
  3327. if tool_widget == self.ncclear_tool.toolName:
  3328. self.ncclear_tool.on_tool_delete()
  3329. # and only if the tool is Paint Tool
  3330. elif tool_widget == self.paint_tool.toolName:
  3331. self.paint_tool.on_tool_delete()
  3332. # and only if the tool is Solder Paste Dispensing Tool
  3333. elif tool_widget == self.paste_tool.toolName:
  3334. self.paste_tool.on_tool_delete()
  3335. else:
  3336. self.on_delete()
  3337. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3338. # some screens you have to be careful where you hover with your mouse.
  3339. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3340. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3341. # Complicated, I know :)
  3342. def on_delete(self):
  3343. """
  3344. Delete the currently selected FlatCAMObjs.
  3345. :return: None
  3346. """
  3347. self.report_usage("on_delete()")
  3348. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3349. # a geometry object before we update it.
  3350. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3351. if self.collection.get_active():
  3352. self.log.debug("on_delete()")
  3353. self.report_usage("on_delete")
  3354. while (self.collection.get_active()):
  3355. self.delete_first_selected()
  3356. self.inform.emit(_("Object(s) deleted ..."))
  3357. # make sure that the selection shape is deleted, too
  3358. self.delete_selection_shape()
  3359. else:
  3360. self.inform.emit(_("Failed. No object(s) selected..."))
  3361. else:
  3362. self.inform.emit(_("Save the work in Editor and try again ..."))
  3363. def on_set_origin(self):
  3364. """
  3365. Set the origin to the left mouse click position
  3366. :return: None
  3367. """
  3368. #display the message for the user
  3369. #and ask him to click on the desired position
  3370. self.report_usage("on_set_origin()")
  3371. self.inform.emit(_('Click to set the origin ...'))
  3372. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3373. def on_jump_to(self):
  3374. """
  3375. Jump to a location by setting the mouse cursor location
  3376. :return:
  3377. """
  3378. self.report_usage("on_jump_to()")
  3379. dia_box = Dialog_box(title=_("Jump to ..."),
  3380. label=_("Enter the coordinates in format X,Y:"),
  3381. icon=QtGui.QIcon('share/jump_to16.png'))
  3382. if dia_box.ok is True:
  3383. try:
  3384. location = eval(dia_box.location)
  3385. if not isinstance(location, tuple):
  3386. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3387. return
  3388. except:
  3389. return
  3390. else:
  3391. return
  3392. self.plotcanvas.fit_center(loc=location)
  3393. cursor = QtGui.QCursor()
  3394. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3395. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3396. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3397. self.inform.emit(_("Done."))
  3398. def on_copy_object(self):
  3399. self.report_usage("on_copy_object()")
  3400. def initialize(obj_init, app):
  3401. obj_init.solid_geometry = obj.solid_geometry
  3402. try:
  3403. if obj.tools:
  3404. obj_init.tools = obj.tools
  3405. except Exception as e:
  3406. log.debug("on_copy_object() --> %s" % str(e))
  3407. def initialize_excellon(obj_init, app):
  3408. obj_init.tools = obj.tools
  3409. # drills are offset, so they need to be deep copied
  3410. obj_init.drills = deepcopy(obj.drills)
  3411. # slots are offset, so they need to be deep copied
  3412. obj_init.slots = deepcopy(obj.slots)
  3413. obj_init.create_geometry()
  3414. for obj in self.collection.get_selected():
  3415. obj_name = obj.options["name"]
  3416. try:
  3417. if isinstance(obj, FlatCAMExcellon):
  3418. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3419. elif isinstance(obj,FlatCAMGerber):
  3420. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3421. elif isinstance(obj,FlatCAMGeometry):
  3422. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3423. except Exception as e:
  3424. return "Operation failed: %s" % str(e)
  3425. def on_copy_object2(self, custom_name):
  3426. def initialize_geometry(obj_init, app):
  3427. obj_init.solid_geometry = obj.solid_geometry
  3428. try:
  3429. if obj.tools:
  3430. obj_init.tools = obj.tools
  3431. except Exception as e:
  3432. log.debug("on_copy_object2() --> %s" % str(e))
  3433. def initialize_gerber(obj_init, app):
  3434. obj_init.solid_geometry = obj.solid_geometry
  3435. obj_init.apertures = deepcopy(obj.apertures)
  3436. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3437. def initialize_excellon(obj_init, app):
  3438. obj_init.tools = obj.tools
  3439. # drills are offset, so they need to be deep copied
  3440. obj_init.drills = deepcopy(obj.drills)
  3441. # slots are offset, so they need to be deep copied
  3442. obj_init.slots = deepcopy(obj.slots)
  3443. obj_init.create_geometry()
  3444. for obj in self.collection.get_selected():
  3445. obj_name = obj.options["name"]
  3446. try:
  3447. if isinstance(obj, FlatCAMExcellon):
  3448. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3449. elif isinstance(obj,FlatCAMGerber):
  3450. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3451. elif isinstance(obj,FlatCAMGeometry):
  3452. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3453. except Exception as e:
  3454. return "Operation failed: %s" % str(e)
  3455. def on_rename_object(self, text):
  3456. self.report_usage("on_rename_object()")
  3457. named_obj = self.collection.get_active()
  3458. for obj in named_obj:
  3459. if obj is list:
  3460. self.on_rename_object(text)
  3461. else:
  3462. try:
  3463. obj.options['name'] = text
  3464. except:
  3465. log.warning("Could not rename the object in the list")
  3466. def on_copy_object_as_geometry(self):
  3467. self.report_usage("on_copy_object_as_geometry()")
  3468. def initialize(obj_init, app):
  3469. obj_init.solid_geometry = obj.solid_geometry
  3470. if obj.tools:
  3471. obj_init.tools = obj.tools
  3472. def initialize_excellon(obj, app):
  3473. objs = self.collection.get_selected()
  3474. FlatCAMGeometry.merge(objs, obj)
  3475. for obj in self.collection.get_selected():
  3476. obj_name = obj.options["name"]
  3477. try:
  3478. if isinstance(obj, FlatCAMExcellon):
  3479. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  3480. else:
  3481. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  3482. except Exception as e:
  3483. return "Operation failed: %s" % str(e)
  3484. def on_set_zero_click(self, event):
  3485. #this function will be available only for mouse left click
  3486. pos =[]
  3487. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3488. if event.button == 1:
  3489. if self.grid_status() == True:
  3490. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3491. else:
  3492. pos = pos_canvas
  3493. x = 0 - pos[0]
  3494. y = 0 - pos[1]
  3495. for obj in self.collection.get_list():
  3496. obj.offset((x,y))
  3497. self.object_changed.emit(obj)
  3498. obj.plot()
  3499. # Update the object bounding box options
  3500. a, b, c, d = obj.bounds()
  3501. obj.options['xmin'] = a
  3502. obj.options['ymin'] = b
  3503. obj.options['xmax'] = c
  3504. obj.options['ymax'] = d
  3505. # self.plot_all(zoom=False)
  3506. self.inform.emit(_('[success] Origin set ...'))
  3507. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  3508. self.should_we_save = True
  3509. def on_selectall(self):
  3510. self.report_usage("on_selectall()")
  3511. # delete the possible selection box around a possible selected object
  3512. self.delete_selection_shape()
  3513. for name in self.collection.get_names():
  3514. self.collection.set_active(name)
  3515. curr_sel_obj = self.collection.get_by_name(name)
  3516. # create the selection box around the selected object
  3517. self.draw_selection_shape(curr_sel_obj)
  3518. def on_preferences(self):
  3519. # add the tab if it was closed
  3520. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  3521. # delete the absolute and relative position and messages in the infobar
  3522. self.ui.position_label.setText("")
  3523. self.ui.rel_position_label.setText("")
  3524. # Switch plot_area to preferences page
  3525. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  3526. self.ui.show()
  3527. def on_flipy(self):
  3528. self.report_usage("on_flipy()")
  3529. obj_list = self.collection.get_selected()
  3530. xminlist = []
  3531. yminlist = []
  3532. xmaxlist = []
  3533. ymaxlist = []
  3534. if not obj_list:
  3535. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  3536. else:
  3537. try:
  3538. # first get a bounding box to fit all
  3539. for obj in obj_list:
  3540. xmin, ymin, xmax, ymax = obj.bounds()
  3541. xminlist.append(xmin)
  3542. yminlist.append(ymin)
  3543. xmaxlist.append(xmax)
  3544. ymaxlist.append(ymax)
  3545. # get the minimum x,y and maximum x,y for all objects selected
  3546. xminimal = min(xminlist)
  3547. yminimal = min(yminlist)
  3548. xmaximal = max(xmaxlist)
  3549. ymaximal = max(ymaxlist)
  3550. px = 0.5 * (xminimal + xmaximal)
  3551. py = 0.5 * (yminimal + ymaximal)
  3552. # execute mirroring
  3553. for obj in obj_list:
  3554. obj.mirror('X', [px, py])
  3555. obj.plot()
  3556. self.object_changed.emit(obj)
  3557. self.inform.emit(_("[success] Flip on Y axis done."))
  3558. except Exception as e:
  3559. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3560. return
  3561. def on_flipx(self):
  3562. self.report_usage("on_flipx()")
  3563. obj_list = self.collection.get_selected()
  3564. xminlist = []
  3565. yminlist = []
  3566. xmaxlist = []
  3567. ymaxlist = []
  3568. if not obj_list:
  3569. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  3570. else:
  3571. try:
  3572. # first get a bounding box to fit all
  3573. for obj in obj_list:
  3574. xmin, ymin, xmax, ymax = obj.bounds()
  3575. xminlist.append(xmin)
  3576. yminlist.append(ymin)
  3577. xmaxlist.append(xmax)
  3578. ymaxlist.append(ymax)
  3579. # get the minimum x,y and maximum x,y for all objects selected
  3580. xminimal = min(xminlist)
  3581. yminimal = min(yminlist)
  3582. xmaximal = max(xmaxlist)
  3583. ymaximal = max(ymaxlist)
  3584. px = 0.5 * (xminimal + xmaximal)
  3585. py = 0.5 * (yminimal + ymaximal)
  3586. # execute mirroring
  3587. for obj in obj_list:
  3588. obj.mirror('Y', [px, py])
  3589. obj.plot()
  3590. self.object_changed.emit(obj)
  3591. self.inform.emit(_("[success] Flip on X axis done."))
  3592. except Exception as e:
  3593. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3594. return
  3595. def on_rotate(self, silent=False, preset=None):
  3596. self.report_usage("on_rotate()")
  3597. obj_list = self.collection.get_selected()
  3598. xminlist = []
  3599. yminlist = []
  3600. xmaxlist = []
  3601. ymaxlist = []
  3602. if not obj_list:
  3603. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  3604. else:
  3605. if silent is False:
  3606. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3607. min=-360, max=360, decimals=4,
  3608. init_val=float(self.defaults['tools_transform_rotate']))
  3609. num, ok = rotatebox.get_value()
  3610. else:
  3611. num = preset
  3612. ok = True
  3613. if ok:
  3614. try:
  3615. # first get a bounding box to fit all
  3616. for obj in obj_list:
  3617. xmin, ymin, xmax, ymax = obj.bounds()
  3618. xminlist.append(xmin)
  3619. yminlist.append(ymin)
  3620. xmaxlist.append(xmax)
  3621. ymaxlist.append(ymax)
  3622. # get the minimum x,y and maximum x,y for all objects selected
  3623. xminimal = min(xminlist)
  3624. yminimal = min(yminlist)
  3625. xmaximal = max(xmaxlist)
  3626. ymaximal = max(ymaxlist)
  3627. px = 0.5 * (xminimal + xmaximal)
  3628. py = 0.5 * (yminimal + ymaximal)
  3629. for sel_obj in obj_list:
  3630. sel_obj.rotate(-float(num), point=(px, py))
  3631. sel_obj.plot()
  3632. self.object_changed.emit(sel_obj)
  3633. self.inform.emit(_("[success] Rotation done."))
  3634. except Exception as e:
  3635. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  3636. return
  3637. def on_skewx(self):
  3638. self.report_usage("on_skewx()")
  3639. obj_list = self.collection.get_selected()
  3640. xminlist = []
  3641. yminlist = []
  3642. if not obj_list:
  3643. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  3644. else:
  3645. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3646. min=-360, max=360, decimals=4,
  3647. init_val=float(self.defaults['tools_transform_skew_x']))
  3648. num, ok = skewxbox.get_value()
  3649. if ok:
  3650. # first get a bounding box to fit all
  3651. for obj in obj_list:
  3652. xmin, ymin, xmax, ymax = obj.bounds()
  3653. xminlist.append(xmin)
  3654. yminlist.append(ymin)
  3655. # get the minimum x,y and maximum x,y for all objects selected
  3656. xminimal = min(xminlist)
  3657. yminimal = min(yminlist)
  3658. for obj in obj_list:
  3659. obj.skew(num, 0, point=(xminimal, yminimal))
  3660. obj.plot()
  3661. self.object_changed.emit(obj)
  3662. self.inform.emit(_("[success] Skew on X axis done."))
  3663. def on_skewy(self):
  3664. self.report_usage("on_skewy()")
  3665. obj_list = self.collection.get_selected()
  3666. xminlist = []
  3667. yminlist = []
  3668. if not obj_list:
  3669. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  3670. else:
  3671. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3672. min=-360, max=360, decimals=4,
  3673. init_val=float(self.defaults['tools_transform_skew_y']))
  3674. num, ok = skewybox.get_value()
  3675. if ok:
  3676. # first get a bounding box to fit all
  3677. for obj in obj_list:
  3678. xmin, ymin, xmax, ymax = obj.bounds()
  3679. xminlist.append(xmin)
  3680. yminlist.append(ymin)
  3681. # get the minimum x,y and maximum x,y for all objects selected
  3682. xminimal = min(xminlist)
  3683. yminimal = min(yminlist)
  3684. for obj in obj_list:
  3685. obj.skew(0, num, point=(xminimal, yminimal))
  3686. obj.plot()
  3687. self.object_changed.emit(obj)
  3688. self.inform.emit(_("[success] Skew on Y axis done."))
  3689. def delete_first_selected(self):
  3690. # Keep this for later
  3691. try:
  3692. name = self.collection.get_active().options["name"]
  3693. except AttributeError:
  3694. self.log.debug("Nothing selected for deletion")
  3695. return
  3696. # Remove plot
  3697. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3698. # self.plotcanvas.auto_adjust_axes()
  3699. # Clear form
  3700. self.setup_component_editor()
  3701. # Remove from dictionary
  3702. self.collection.delete_active()
  3703. self.inform.emit("Object deleted: %s" % name)
  3704. def on_plots_updated(self):
  3705. """
  3706. Callback used to report when the plots have changed.
  3707. Adjust axes and zooms to fit.
  3708. :return: None
  3709. """
  3710. # self.plotcanvas.auto_adjust_axes()
  3711. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3712. self.on_zoom_fit(None)
  3713. # TODO: Rework toolbar 'clear', 'replot' functions
  3714. def on_toolbar_replot(self):
  3715. """
  3716. Callback for toolbar button. Re-plots all objects.
  3717. :return: None
  3718. """
  3719. self.report_usage("on_toolbar_replot")
  3720. self.log.debug("on_toolbar_replot()")
  3721. try:
  3722. self.collection.get_active().read_form()
  3723. except AttributeError:
  3724. self.log.debug("on_toolbar_replot(): AttributeError")
  3725. pass
  3726. self.plot_all()
  3727. def on_row_activated(self, index):
  3728. if index.isValid():
  3729. if index.internalPointer().parent_item != self.collection.root_item:
  3730. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3731. def grid_status(self):
  3732. if self.ui.grid_snap_btn.isChecked():
  3733. return 1
  3734. else:
  3735. return 0
  3736. def populate_cmenu_grids(self):
  3737. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3738. self.ui.cmenu_gridmenu.clear()
  3739. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  3740. for grid in sorted_list:
  3741. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  3742. action.triggered.connect(self.set_grid)
  3743. self.ui.cmenu_gridmenu.addSeparator()
  3744. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), "Add")
  3745. grid_add.triggered.connect(self.on_grid_add)
  3746. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), "Delete")
  3747. grid_delete.triggered.connect(self.on_grid_delete)
  3748. def set_grid(self):
  3749. self.ui.grid_gap_x_entry.setText(self.sender().text())
  3750. self.ui.grid_gap_y_entry.setText(self.sender().text())
  3751. def on_grid_add(self):
  3752. ## Current application units in lower Case
  3753. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3754. grid_add_popup = FCInputDialog(title="New Grid ...",
  3755. text='Enter a Grid VAlue:',
  3756. min=0.0000, max=99.9999, decimals=4)
  3757. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  3758. val, ok = grid_add_popup.get_value()
  3759. if ok:
  3760. if float(val) == 0:
  3761. self.inform.emit(
  3762. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  3763. return
  3764. else:
  3765. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  3766. self.defaults["global_grid_context_menu"][str(units)].append(val)
  3767. self.inform.emit(
  3768. _("[success] New Grid added ..."))
  3769. else:
  3770. self.inform.emit(
  3771. _("[WARNING_NOTCL] Grid already exists ..."))
  3772. else:
  3773. self.inform.emit(
  3774. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  3775. def on_grid_delete(self):
  3776. ## Current application units in lower Case
  3777. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3778. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  3779. text='Enter a Grid Value:',
  3780. min=0.0000, max=99.9999, decimals=4)
  3781. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  3782. val, ok = grid_del_popup.get_value()
  3783. if ok:
  3784. if float(val) == 0:
  3785. self.inform.emit(
  3786. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  3787. return
  3788. else:
  3789. try:
  3790. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  3791. except ValueError:
  3792. self.inform.emit(
  3793. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  3794. return
  3795. self.inform.emit(
  3796. _("[success] Grid Value deleted ..."))
  3797. else:
  3798. self.inform.emit(
  3799. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  3800. def on_shortcut_list(self):
  3801. self.report_usage("on_shortcut_list()")
  3802. # add the tab if it was closed
  3803. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  3804. # delete the absolute and relative position and messages in the infobar
  3805. self.ui.position_label.setText("")
  3806. self.ui.rel_position_label.setText("")
  3807. # Switch plot_area to preferences page
  3808. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  3809. self.ui.show()
  3810. def on_select_tab(self, name):
  3811. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  3812. if self.ui.splitter.sizes()[0] == 0:
  3813. self.ui.splitter.setSizes([1, 1])
  3814. else:
  3815. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  3816. self.ui.splitter.setSizes([0, 1])
  3817. if name == 'project':
  3818. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3819. elif name == 'selected':
  3820. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3821. elif name == 'tool':
  3822. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  3823. def on_copy_name(self):
  3824. self.report_usage("on_copy_name()")
  3825. obj = self.collection.get_active()
  3826. try:
  3827. name = obj.options["name"]
  3828. except AttributeError:
  3829. log.debug("on_copy_name() --> No object selected to copy it's name")
  3830. self.inform.emit(_("[WARNING_NOTCL]No object selected to copy it's name"))
  3831. return
  3832. self.clipboard.setText(name)
  3833. self.inform.emit(_("Name copied on clipboard ..."))
  3834. def on_mouse_click_over_plot(self, event):
  3835. """
  3836. Default actions are:
  3837. :param event: Contains information about the event, like which button
  3838. was clicked, the pixel coordinates and the axes coordinates.
  3839. :return: None
  3840. """
  3841. self.pos = []
  3842. # So it can receive key presses
  3843. self.plotcanvas.vispy_canvas.native.setFocus()
  3844. # Set the mouse button for panning
  3845. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3846. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3847. if self.grid_status() == True:
  3848. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3849. self.app_cursor.enabled = True
  3850. else:
  3851. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3852. self.app_cursor.enabled = False
  3853. try:
  3854. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3855. if event.button == 1:
  3856. # Reset here the relative coordinates so there is a new reference on the click position
  3857. if self.rel_point1 is None:
  3858. self.rel_point1 = self.pos
  3859. else:
  3860. self.rel_point2 = copy(self.rel_point1)
  3861. self.rel_point1 = self.pos
  3862. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3863. if modifiers == QtCore.Qt.ShiftModifier:
  3864. # do not auto open the Project Tab
  3865. self.click_noproject = True
  3866. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3867. return
  3868. self.on_mouse_move_over_plot(event, origin_click=True)
  3869. except Exception as e:
  3870. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3871. def on_double_click_over_plot(self, event):
  3872. self.doubleclick = True
  3873. def on_mouse_move_over_plot(self, event, origin_click=None):
  3874. """
  3875. Callback for the mouse motion event over the plot. This event is generated
  3876. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3877. For details, see: http://matplotlib.org/users/event_handling.html
  3878. :param event: Contains information about the event.
  3879. :param origin_click
  3880. :return: None
  3881. """
  3882. # So it can receive key presses
  3883. self.plotcanvas.vispy_canvas.native.setFocus()
  3884. self.pos_jump = event.pos
  3885. if origin_click is True:
  3886. pass
  3887. else:
  3888. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3889. if event.button == 2:
  3890. self.panning_action = True
  3891. return
  3892. else:
  3893. self.panning_action = False
  3894. if self.rel_point1 is not None:
  3895. try: # May fail in case mouse not within axes
  3896. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3897. if self.grid_status():
  3898. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3899. self.app_cursor.enabled = True
  3900. # Update cursor
  3901. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3902. else:
  3903. pos = (pos_canvas[0], pos_canvas[1])
  3904. self.app_cursor.enabled = False
  3905. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3906. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3907. dx = pos[0] - self.rel_point1[0]
  3908. dy = pos[1] - self.rel_point1[1]
  3909. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3910. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3911. self.mouse = [pos[0], pos[1]]
  3912. # if the mouse is moved and the LMB is clicked then the action is a selection
  3913. if event.is_dragging == 1 and event.button == 1:
  3914. self.delete_selection_shape()
  3915. if dx < 0:
  3916. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3917. face_color=self.defaults['global_alt_sel_fill'])
  3918. self.selection_type = False
  3919. else:
  3920. self.draw_moving_selection_shape(self.pos, pos)
  3921. self.selection_type = True
  3922. # hover effect - enabled in Preferences -> General -> GUI Settings
  3923. if self.defaults['global_hover']:
  3924. for obj in self.collection.get_list():
  3925. try:
  3926. # select the object(s) only if it is enabled (plotted)
  3927. if obj.options['plot']:
  3928. if obj not in self.collection.get_selected():
  3929. poly_obj = Polygon(
  3930. [(obj.options['xmin'], obj.options['ymin']),
  3931. (obj.options['xmax'], obj.options['ymin']),
  3932. (obj.options['xmax'], obj.options['ymax']),
  3933. (obj.options['xmin'], obj.options['ymax'])]
  3934. )
  3935. if Point(pos).within(poly_obj):
  3936. if obj.isHovering is False:
  3937. obj.isHovering = True
  3938. obj.notHovering = True
  3939. # create the selection box around the selected object
  3940. self.draw_hover_shape(obj, color='#d1e0e0')
  3941. else:
  3942. if obj.notHovering is True:
  3943. obj.notHovering = False
  3944. obj.isHovering = False
  3945. self.delete_hover_shape()
  3946. except:
  3947. # the Exception here will happen if we try to select on screen and we have an
  3948. # newly (and empty) just created Geometry or Excellon object that do not have the
  3949. # xmin, xmax, ymin, ymax options.
  3950. # In this case poly_obj creation (see above) will fail
  3951. pass
  3952. except:
  3953. self.ui.position_label.setText("")
  3954. self.ui.rel_position_label.setText("")
  3955. self.mouse = None
  3956. def on_mouse_click_release_over_plot(self, event):
  3957. """
  3958. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3959. and has been registered in ''self.__init__()''.
  3960. :param event: contains information about the event.
  3961. :return:
  3962. """
  3963. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3964. if self.grid_status():
  3965. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3966. else:
  3967. pos = (pos_canvas[0], pos_canvas[1])
  3968. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3969. # canvas menu
  3970. try:
  3971. if event.button == 2: # right click
  3972. if self.panning_action is True:
  3973. self.panning_action = False
  3974. else:
  3975. self.cursor = QtGui.QCursor()
  3976. self.populate_cmenu_grids()
  3977. self.ui.popMenu.popup(self.cursor.pos())
  3978. except Exception as e:
  3979. log.warning("Error: %s" % str(e))
  3980. return
  3981. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3982. # selection and then select a type of selection ("enclosing" or "touching")
  3983. try:
  3984. if event.button == 1: # left click
  3985. if self.doubleclick is True:
  3986. self.doubleclick = False
  3987. if self.collection.get_selected():
  3988. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3989. if self.ui.splitter.sizes()[0] == 0:
  3990. self.ui.splitter.setSizes([1, 1])
  3991. # delete the selection shape(S) as it may be in the way
  3992. self.delete_selection_shape()
  3993. self.delete_hover_shape()
  3994. else:
  3995. if self.selection_type is not None:
  3996. self.selection_area_handler(self.pos, pos, self.selection_type)
  3997. self.selection_type = None
  3998. else:
  3999. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4000. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  4001. # and if it's not selected then it will be selected
  4002. if modifiers == QtCore.Qt.ControlModifier:
  4003. # If there is no active command (self.command_active is None) then we check if we clicked on
  4004. # a object by checking the bounding limits against mouse click position
  4005. if self.command_active is None:
  4006. self.select_objects(key='CTRL')
  4007. self.delete_hover_shape()
  4008. else:
  4009. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  4010. # checking the bounding limits against mouse click position
  4011. if self.command_active is None:
  4012. self.select_objects()
  4013. self.delete_hover_shape()
  4014. except Exception as e:
  4015. log.warning("Error: %s" % str(e))
  4016. return
  4017. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4018. """
  4019. :param start_pos: mouse position when the selection LMB click was done
  4020. :param end_pos: mouse position when the left mouse button is released
  4021. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4022. :return:
  4023. """
  4024. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4025. self.delete_selection_shape()
  4026. for obj in self.collection.get_list():
  4027. try:
  4028. # select the object(s) only if it is enabled (plotted)
  4029. if obj.options['plot']:
  4030. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4031. (obj.options['xmax'], obj.options['ymin']),
  4032. (obj.options['xmax'], obj.options['ymax']),
  4033. (obj.options['xmin'], obj.options['ymax'])])
  4034. if sel_type is True:
  4035. if poly_obj.within(poly_selection):
  4036. # create the selection box around the selected object
  4037. self.draw_selection_shape(obj)
  4038. self.collection.set_active(obj.options['name'])
  4039. else:
  4040. if poly_selection.intersects(poly_obj):
  4041. # create the selection box around the selected object
  4042. self.draw_selection_shape(obj)
  4043. self.collection.set_active(obj.options['name'])
  4044. except:
  4045. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4046. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4047. # In this case poly_obj creation (see above) will fail
  4048. pass
  4049. def select_objects(self, key=None):
  4050. # list where we store the overlapped objects under our mouse left click position
  4051. objects_under_the_click_list = []
  4052. # Populate the list with the overlapped objects on the click position
  4053. curr_x, curr_y = self.pos
  4054. for obj in self.all_objects_list:
  4055. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4056. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4057. if obj.options['name'] not in objects_under_the_click_list:
  4058. if obj.options['plot']:
  4059. # add objects to the objects_under_the_click list only if the object is plotted
  4060. # (active and not disabled)
  4061. objects_under_the_click_list.append(obj.options['name'])
  4062. try:
  4063. # If there is no element in the overlapped objects list then make everyone inactive
  4064. # because we selected "nothing"
  4065. if not objects_under_the_click_list:
  4066. self.collection.set_all_inactive()
  4067. # delete the possible selection box around a possible selected object
  4068. self.delete_selection_shape()
  4069. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  4070. # only when working on App
  4071. if self.call_source == 'app':
  4072. if self.click_noproject is False:
  4073. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4074. else:
  4075. # restore auto open the Project Tab
  4076. self.click_noproject = False
  4077. # delete any text in the status bar, implicitly the last object name that was selected
  4078. self.inform.emit("")
  4079. else:
  4080. self.call_source = 'app'
  4081. else:
  4082. # case when there is only an object under the click and we toggle it
  4083. if len(objects_under_the_click_list) == 1:
  4084. if self.collection.get_active() is None :
  4085. self.collection.set_active(objects_under_the_click_list[0])
  4086. # create the selection box around the selected object
  4087. curr_sel_obj = self.collection.get_active()
  4088. self.draw_selection_shape(curr_sel_obj)
  4089. # self.inform.emit('[selected] %s: %s selected' %
  4090. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4091. if curr_sel_obj.kind == 'gerber':
  4092. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4093. color='green', name=str(curr_sel_obj.options['name'])))
  4094. elif curr_sel_obj.kind == 'excellon':
  4095. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4096. color='brown', name=str(curr_sel_obj.options['name'])))
  4097. elif curr_sel_obj.kind == 'cncjob':
  4098. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4099. color='blue', name=str(curr_sel_obj.options['name'])))
  4100. elif curr_sel_obj.kind == 'geometry':
  4101. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4102. color='red', name=str(curr_sel_obj.options['name'])))
  4103. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  4104. self.collection.set_all_inactive()
  4105. self.delete_selection_shape()
  4106. self.collection.set_active(objects_under_the_click_list[0])
  4107. # create the selection box around the selected object
  4108. curr_sel_obj = self.collection.get_active()
  4109. self.draw_selection_shape(curr_sel_obj)
  4110. # self.inform.emit('[selected] %s: %s selected' %
  4111. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4112. if curr_sel_obj.kind == 'gerber':
  4113. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4114. color='green', name=str(curr_sel_obj.options['name'])))
  4115. elif curr_sel_obj.kind == 'excellon':
  4116. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4117. color='brown', name=str(curr_sel_obj.options['name'])))
  4118. elif curr_sel_obj.kind == 'cncjob':
  4119. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4120. color='blue', name=str(curr_sel_obj.options['name'])))
  4121. elif curr_sel_obj.kind == 'geometry':
  4122. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4123. color='red', name=str(curr_sel_obj.options['name'])))
  4124. else:
  4125. self.collection.set_all_inactive()
  4126. self.delete_selection_shape()
  4127. if self.call_source == 'app':
  4128. # delete any text in the status bar, implicitly the last object name that was selected
  4129. self.inform.emit("")
  4130. else:
  4131. self.call_source = 'app'
  4132. else:
  4133. # If there is no selected object
  4134. # make active the first element of the overlapped objects list
  4135. if self.collection.get_active() is None:
  4136. self.collection.set_active(objects_under_the_click_list[0])
  4137. name_sel_obj = self.collection.get_active().options['name']
  4138. # In case that there is a selected object but it is not in the overlapped object list
  4139. # make that object inactive and activate the first element in the overlapped object list
  4140. if name_sel_obj not in objects_under_the_click_list:
  4141. self.collection.set_inactive(name_sel_obj)
  4142. name_sel_obj = objects_under_the_click_list[0]
  4143. self.collection.set_active(name_sel_obj)
  4144. else:
  4145. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  4146. self.collection.set_all_inactive()
  4147. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  4148. len(objects_under_the_click_list)])
  4149. curr_sel_obj = self.collection.get_active()
  4150. # delete the possible selection box around a possible selected object
  4151. self.delete_selection_shape()
  4152. # create the selection box around the selected object
  4153. self.draw_selection_shape(curr_sel_obj)
  4154. # self.inform.emit('[selected] %s: %s selected' %
  4155. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4156. if curr_sel_obj.kind == 'gerber':
  4157. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4158. color='green', name=str(curr_sel_obj.options['name'])))
  4159. elif curr_sel_obj.kind == 'excellon':
  4160. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4161. color='brown', name=str(curr_sel_obj.options['name'])))
  4162. elif curr_sel_obj.kind == 'cncjob':
  4163. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4164. color='blue', name=str(curr_sel_obj.options['name'])))
  4165. elif curr_sel_obj.kind == 'geometry':
  4166. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4167. color='red', name=str(curr_sel_obj.options['name'])))
  4168. # for obj in self.collection.get_list():
  4169. # obj.plot()
  4170. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  4171. # TODO: on selected objects change the object colors and do not draw the selection box
  4172. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  4173. except Exception as e:
  4174. log.error("[ERROR] Something went bad. %s" % str(e))
  4175. return
  4176. def delete_hover_shape(self):
  4177. self.hover_shapes.clear()
  4178. self.hover_shapes.redraw()
  4179. def draw_hover_shape(self, sel_obj, color=None):
  4180. """
  4181. :param sel_obj: the object for which the hover shape must be drawn
  4182. :return:
  4183. """
  4184. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4185. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4186. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4187. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4188. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  4189. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4190. hover_rect = hover_rect.buffer(-0.1)
  4191. hover_rect = hover_rect.buffer(0.2)
  4192. else:
  4193. hover_rect = hover_rect.buffer(-0.00393)
  4194. hover_rect = hover_rect.buffer(0.00787)
  4195. if color:
  4196. face = Color(color)
  4197. face.alpha = 0.2
  4198. outline = Color(color, alpha=0.8)
  4199. else:
  4200. face = Color(self.defaults['global_sel_fill'])
  4201. face.alpha = 0.2
  4202. outline = self.defaults['global_sel_line']
  4203. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  4204. def delete_selection_shape(self):
  4205. self.move_tool.sel_shapes.clear()
  4206. self.move_tool.sel_shapes.redraw()
  4207. def draw_selection_shape(self, sel_obj, color=None):
  4208. """
  4209. :param sel_obj: the object for which the selection shape must be drawn
  4210. :return:
  4211. """
  4212. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4213. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4214. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4215. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4216. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4217. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4218. sel_rect = sel_rect.buffer(-0.1)
  4219. sel_rect = sel_rect.buffer(0.2)
  4220. else:
  4221. sel_rect = sel_rect.buffer(-0.00393)
  4222. sel_rect = sel_rect.buffer(0.00787)
  4223. if color:
  4224. face = Color(color, alpha=0.2)
  4225. outline = Color(color, alpha=0.8)
  4226. else:
  4227. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  4228. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  4229. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=outline,
  4230. face_color=face, update=True, layer=0, tolerance=None))
  4231. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  4232. """
  4233. :param old_coords: old coordinates
  4234. :param coords: new coordinates
  4235. :return:
  4236. """
  4237. if 'color' in kwargs:
  4238. color = kwargs['color']
  4239. else:
  4240. color = self.defaults['global_sel_line']
  4241. if 'face_color' in kwargs:
  4242. face_color = kwargs['face_color']
  4243. else:
  4244. face_color = self.defaults['global_sel_fill']
  4245. x0, y0 = old_coords
  4246. x1, y1 = coords
  4247. pt1 = (x0, y0)
  4248. pt2 = (x1, y0)
  4249. pt3 = (x1, y1)
  4250. pt4 = (x0, y1)
  4251. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4252. color_t = Color(face_color)
  4253. color_t.alpha = 0.3
  4254. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  4255. layer=0, tolerance=None)
  4256. def on_file_new_click(self):
  4257. if self.collection.get_list() and self.should_we_save:
  4258. msgbox = QtWidgets.QMessageBox()
  4259. # msgbox.setText("<B>Save changes ...</B>")
  4260. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  4261. "Creating a New project will delete them.\n"
  4262. "Do you want to Save the project?"))
  4263. msgbox.setWindowTitle(_("Save changes"))
  4264. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4265. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  4266. QtWidgets.QMessageBox.No)
  4267. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4268. response = msgbox.exec_()
  4269. if response == QtWidgets.QMessageBox.Yes:
  4270. self.on_file_saveprojectas()
  4271. elif response == QtWidgets.QMessageBox.Cancel:
  4272. return
  4273. self.on_file_new()
  4274. else:
  4275. self.on_file_new()
  4276. self.inform.emit(_("[success] New Project created..."))
  4277. def on_file_new(self):
  4278. """
  4279. Callback for menu item File->New. Returns the application to its
  4280. startup state. This method is thread-safe.
  4281. :return: None
  4282. """
  4283. self.report_usage("on_file_new")
  4284. # Remove everything from memory
  4285. App.log.debug("on_file_new()")
  4286. # Clear pool
  4287. self.clear_pool()
  4288. #delete shapes left drawn from mark shape_collections, if any
  4289. for obj in self.collection.get_list():
  4290. try:
  4291. obj.mark_shapes.enabled = False
  4292. obj.mark_shapes.clear(update=True)
  4293. except:
  4294. pass
  4295. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  4296. self.init_tcl()
  4297. self.delete_selection_shape()
  4298. self.collection.delete_all()
  4299. self.setup_component_editor()
  4300. # Clear project filename
  4301. self.project_filename = None
  4302. # Load the application defaults
  4303. self.load_defaults(filename='current_defaults')
  4304. # Re-fresh project options
  4305. self.on_options_app2project()
  4306. # Init Tools
  4307. self.init_tools()
  4308. # Close any Tabs opened in the Plot Tab Area section
  4309. for index in range(self.ui.plot_tab_area.count()):
  4310. self.ui.plot_tab_area.closeTab(index)
  4311. # for whatever reason previous command does not close the last tab so I do it manually
  4312. self.ui.plot_tab_area.closeTab(0)
  4313. # # And then add again the Plot Area
  4314. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4315. self.ui.plot_tab_area.protectTab(0)
  4316. # take the focus of the Notebook on Project Tab.
  4317. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4318. def obj_properties(self):
  4319. self.report_usage("obj_properties()")
  4320. self.properties_tool.run(toggle=False)
  4321. def on_project_context_save(self):
  4322. obj = self.collection.get_active()
  4323. if type(obj) == FlatCAMGeometry:
  4324. self.on_file_exportdxf()
  4325. elif type(obj) == FlatCAMExcellon:
  4326. self.on_file_saveexcellon()
  4327. elif type(obj) == FlatCAMCNCjob:
  4328. obj.on_exportgcode_button_click()
  4329. elif type(obj) == FlatCAMGerber:
  4330. self.on_file_savegerber()
  4331. def obj_move(self):
  4332. self.report_usage("obj_move()")
  4333. self.move_tool.run()
  4334. def on_fileopengerber(self):
  4335. """
  4336. File menu callback for opening a Gerber.
  4337. :return: None
  4338. """
  4339. self.report_usage("on_fileopengerber")
  4340. App.log.debug("on_fileopengerber()")
  4341. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4342. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4343. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  4344. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4345. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4346. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4347. "Allegro Files (*.art);;" \
  4348. "Mentor Files (*.pho *.gdo);;" \
  4349. "All Files (*.*)"
  4350. try:
  4351. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  4352. directory=self.get_last_folder(), filter=_filter_)
  4353. except TypeError:
  4354. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  4355. filenames = [str(filename) for filename in filenames]
  4356. if len(filenames) == 0:
  4357. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  4358. else:
  4359. for filename in filenames:
  4360. if filename != '':
  4361. self.worker_task.emit({'fcn': self.open_gerber,
  4362. 'params': [filename]})
  4363. def on_fileopenexcellon(self):
  4364. """
  4365. File menu callback for opening an Excellon file.
  4366. :return: None
  4367. """
  4368. self.report_usage("on_fileopenexcellon")
  4369. App.log.debug("on_fileopenexcellon()")
  4370. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  4371. "All Files (*.*)"
  4372. try:
  4373. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  4374. directory=self.get_last_folder(), filter=_filter_)
  4375. except TypeError:
  4376. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  4377. filenames = [str(filename) for filename in filenames]
  4378. if len(filenames) == 0:
  4379. self.inform.emit(_("[WARNING_NOTCL]Open Excellon cancelled."))
  4380. else:
  4381. for filename in filenames:
  4382. if filename != '':
  4383. self.worker_task.emit({'fcn': self.open_excellon,
  4384. 'params': [filename]})
  4385. def on_fileopengcode(self):
  4386. """
  4387. File menu call back for opening gcode.
  4388. :return: None
  4389. """
  4390. self.report_usage("on_fileopengcode")
  4391. App.log.debug("on_fileopengcode()")
  4392. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  4393. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  4394. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  4395. "All Files (*.*)"
  4396. try:
  4397. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  4398. directory=self.get_last_folder(), filter=_filter_)
  4399. except TypeError:
  4400. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  4401. filenames = [str(filename) for filename in filenames]
  4402. if len(filenames) == 0:
  4403. self.inform.emit(_("[WARNING_NOTCL]Open G-Code cancelled."))
  4404. else:
  4405. for filename in filenames:
  4406. if filename != '':
  4407. self.worker_task.emit({'fcn': self.open_gcode,
  4408. 'params': [filename]})
  4409. def on_file_openproject(self):
  4410. """
  4411. File menu callback for opening a project.
  4412. :return: None
  4413. """
  4414. self.report_usage("on_file_openproject")
  4415. App.log.debug("on_file_openproject()")
  4416. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  4417. try:
  4418. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  4419. directory=self.get_last_folder(), filter=_filter_)
  4420. except TypeError:
  4421. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter = _filter_)
  4422. # The Qt methods above will return a QString which can cause problems later.
  4423. # So far json.dump() will fail to serialize it.
  4424. # TODO: Improve the serialization methods and remove this fix.
  4425. filename = str(filename)
  4426. if filename == "":
  4427. self.inform.emit(_("[WARNING_NOTCL]Open Project cancelled."))
  4428. else:
  4429. # self.worker_task.emit({'fcn': self.open_project,
  4430. # 'params': [filename]})
  4431. # The above was failing because open_project() is not
  4432. # thread safe. The new_project()
  4433. self.open_project(filename)
  4434. def on_file_openconfig(self):
  4435. """
  4436. File menu callback for opening a config file.
  4437. :return: None
  4438. """
  4439. self.report_usage("on_file_openconfig")
  4440. App.log.debug("on_file_openconfig()")
  4441. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  4442. try:
  4443. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  4444. directory=self.data_path, filter=_filter_)
  4445. except TypeError:
  4446. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  4447. filter = _filter_)
  4448. if filename == "":
  4449. self.inform.emit(_("[WARNING_NOTCL]Open Config cancelled."))
  4450. else:
  4451. self.open_config_file(filename)
  4452. def on_file_exportsvg(self):
  4453. """
  4454. Callback for menu item File->Export SVG.
  4455. :return: None
  4456. """
  4457. self.report_usage("on_file_exportsvg")
  4458. App.log.debug("on_file_exportsvg()")
  4459. obj = self.collection.get_active()
  4460. if obj is None:
  4461. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  4462. msg = _("Please Select a Geometry object to export")
  4463. msgbox = QtWidgets.QMessageBox()
  4464. msgbox.setInformativeText(msg)
  4465. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4466. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4467. msgbox.exec_()
  4468. return
  4469. # Check for more compatible types and add as required
  4470. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  4471. and not isinstance(obj, FlatCAMExcellon)):
  4472. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  4473. msgbox = QtWidgets.QMessageBox()
  4474. msgbox.setInformativeText(msg)
  4475. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4476. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4477. msgbox.exec_()
  4478. return
  4479. name = self.collection.get_active().options["name"]
  4480. filter = "SVG File (*.svg);;All Files (*.*)"
  4481. try:
  4482. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4483. caption=_("Export SVG"),
  4484. directory=self.get_last_save_folder() + '/' + str(name),
  4485. filter=filter)
  4486. except TypeError:
  4487. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=filter)
  4488. filename = str(filename)
  4489. if filename == "":
  4490. self.inform.emit(_("[WARNING_NOTCL]Export SVG cancelled."))
  4491. return
  4492. else:
  4493. self.export_svg(name, filename)
  4494. self.file_saved.emit("SVG", filename)
  4495. def on_file_exportpng(self):
  4496. self.report_usage("on_file_exportpng")
  4497. App.log.debug("on_file_exportpng()")
  4498. image = _screenshot()
  4499. data = np.asarray(image)
  4500. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  4501. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  4502. return
  4503. filter_ = "PNG File (*.png);;All Files (*.*)"
  4504. try:
  4505. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4506. caption=_("Export PNG Image"),
  4507. directory=self.get_last_save_folder() + '/png_' + str(self.date).replace('-', ''),
  4508. filter=filter_)
  4509. except TypeError:
  4510. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  4511. filename = str(filename)
  4512. if filename == "":
  4513. self.inform.emit(_("Export PNG cancelled."))
  4514. return
  4515. else:
  4516. write_png(filename, data)
  4517. self.file_saved.emit("png", filename)
  4518. def on_file_savegerber(self):
  4519. """
  4520. Callback for menu item File->Export Gerber.
  4521. :return: None
  4522. """
  4523. self.report_usage("on_file_savegerber")
  4524. App.log.debug("on_file_savegerber()")
  4525. obj = self.collection.get_active()
  4526. if obj is None:
  4527. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  4528. return
  4529. # Check for more compatible types and add as required
  4530. if not isinstance(obj, FlatCAMGerber):
  4531. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  4532. return
  4533. name = self.collection.get_active().options["name"]
  4534. filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  4535. try:
  4536. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4537. caption="Save Gerber source file",
  4538. directory=self.get_last_save_folder() + '/' + name,
  4539. filter=filter)
  4540. except TypeError:
  4541. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=filter)
  4542. filename = str(filename)
  4543. if filename == "":
  4544. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  4545. return
  4546. else:
  4547. self.save_source_file(name, filename)
  4548. self.file_saved.emit("Gerber", filename)
  4549. def on_file_saveexcellon(self):
  4550. """
  4551. Callback for menu item File->Export Gerber.
  4552. :return: None
  4553. """
  4554. self.report_usage("on_file_saveexcellon")
  4555. App.log.debug("on_file_saveexcellon()")
  4556. obj = self.collection.get_active()
  4557. if obj is None:
  4558. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  4559. return
  4560. # Check for more compatible types and add as required
  4561. if not isinstance(obj, FlatCAMExcellon):
  4562. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  4563. return
  4564. name = self.collection.get_active().options["name"]
  4565. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4566. try:
  4567. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4568. caption=_("Save Excellon source file"),
  4569. directory=self.get_last_save_folder() + '/' + name,
  4570. filter=filter)
  4571. except TypeError:
  4572. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=filter)
  4573. filename = str(filename)
  4574. if filename == "":
  4575. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  4576. return
  4577. else:
  4578. self.save_source_file(name, filename)
  4579. self.file_saved.emit("Excellon", filename)
  4580. def on_file_exportexcellon(self):
  4581. """
  4582. Callback for menu item File->Export SVG.
  4583. :return: None
  4584. """
  4585. self.report_usage("on_file_exportexcellon")
  4586. App.log.debug("on_file_exportexcellon()")
  4587. obj = self.collection.get_active()
  4588. if obj is None:
  4589. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  4590. return
  4591. # Check for more compatible types and add as required
  4592. if not isinstance(obj, FlatCAMExcellon):
  4593. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  4594. return
  4595. name = self.collection.get_active().options["name"]
  4596. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4597. try:
  4598. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4599. caption=_("Export Excellon"),
  4600. directory=self.get_last_save_folder() + '/' + name,
  4601. filter=filter)
  4602. except TypeError:
  4603. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=filter)
  4604. filename = str(filename)
  4605. if filename == "":
  4606. self.inform.emit(_("[WARNING_NOTCL]Export Excellon cancelled."))
  4607. return
  4608. else:
  4609. self.export_excellon(name, filename)
  4610. self.file_saved.emit("Excellon", filename)
  4611. def on_file_exportdxf(self):
  4612. """
  4613. Callback for menu item File->Export DXF.
  4614. :return: None
  4615. """
  4616. self.report_usage("on_file_exportdxf")
  4617. App.log.debug("on_file_exportdxf()")
  4618. obj = self.collection.get_active()
  4619. if obj is None:
  4620. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  4621. msg = _("Please Select a Geometry object to export")
  4622. msgbox = QtWidgets.QMessageBox()
  4623. msgbox.setInformativeText(msg)
  4624. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4625. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4626. msgbox.exec_()
  4627. return
  4628. # Check for more compatible types and add as required
  4629. if not isinstance(obj, FlatCAMGeometry):
  4630. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  4631. msgbox = QtWidgets.QMessageBox()
  4632. msgbox.setInformativeText(msg)
  4633. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4634. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4635. msgbox.exec_()
  4636. return
  4637. name = self.collection.get_active().options["name"]
  4638. filter = "DXF File (*.DXF);;All Files (*.*)"
  4639. try:
  4640. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4641. caption=_("Export DXF"),
  4642. directory=self.get_last_save_folder() + '/' + name,
  4643. filter=filter)
  4644. except TypeError:
  4645. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"), filter=filter)
  4646. filename = str(filename)
  4647. if filename == "":
  4648. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  4649. return
  4650. else:
  4651. self.export_dxf(name, filename)
  4652. self.file_saved.emit("DXF", filename)
  4653. def on_file_importsvg(self, type_of_obj):
  4654. """
  4655. Callback for menu item File->Import SVG.
  4656. :param type_of_obj: to import the SVG as Geometry or as Gerber
  4657. :type type_of_obj: str
  4658. :return: None
  4659. """
  4660. self.report_usage("on_file_importsvg")
  4661. App.log.debug("on_file_importsvg()")
  4662. filter = "SVG File (*.svg);;All Files (*.*)"
  4663. try:
  4664. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  4665. directory=self.get_last_folder(), filter=filter)
  4666. except TypeError:
  4667. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"), filter=filter)
  4668. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4669. type_of_obj = "geometry"
  4670. filenames = [str(filename) for filename in filenames]
  4671. if len(filenames) == 0:
  4672. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  4673. else:
  4674. for filename in filenames:
  4675. if filename != '':
  4676. self.worker_task.emit({'fcn': self.import_svg,
  4677. 'params': [filename, type_of_obj]})
  4678. def on_file_importdxf(self, type_of_obj):
  4679. """
  4680. Callback for menu item File->Import DXF.
  4681. :param type_of_obj: to import the DXF as Geometry or as Gerber
  4682. :type type_of_obj: str
  4683. :return: None
  4684. """
  4685. self.report_usage("on_file_importdxf")
  4686. App.log.debug("on_file_importdxf()")
  4687. filter = "DXF File (*.DXF);;All Files (*.*)"
  4688. try:
  4689. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  4690. directory=self.get_last_folder(), filter=filter)
  4691. except TypeError:
  4692. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"), filter=filter)
  4693. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4694. type_of_obj = "geometry"
  4695. filenames = [str(filename) for filename in filenames]
  4696. if len(filenames) == 0:
  4697. self.inform.emit(_("[WARNING_NOTCL]Open DXF cancelled."))
  4698. else:
  4699. for filename in filenames:
  4700. if filename != '':
  4701. self.worker_task.emit({'fcn': self.import_dxf,
  4702. 'params': [filename, type_of_obj]})
  4703. ###################################################################################################################
  4704. ### The following section has the functions that are displayed are call the Editoe tab CNCJob Tab #################
  4705. ###################################################################################################################
  4706. def init_code_editor(self, name):
  4707. # Signals section
  4708. # Disconnect the old signals
  4709. self.ui.buttonOpen.clicked.disconnect()
  4710. self.ui.buttonSave.clicked.disconnect()
  4711. # add the tab if it was closed
  4712. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  4713. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  4714. # delete the absolute and relative position and messages in the infobar
  4715. self.ui.position_label.setText("")
  4716. self.ui.rel_position_label.setText("")
  4717. # first clear previous text in text editor (if any)
  4718. self.ui.code_editor.clear()
  4719. self.toggle_codeeditor = True
  4720. # Switch plot_area to CNCJob tab
  4721. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  4722. def on_view_source(self):
  4723. try:
  4724. obj = self.collection.get_active()
  4725. except:
  4726. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  4727. return 'fail'
  4728. # then append the text from GCode to the text editor
  4729. try:
  4730. file = StringIO(obj.source_file)
  4731. except AttributeError:
  4732. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  4733. return 'fail'
  4734. if obj.kind == 'gerber':
  4735. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  4736. elif obj.kind == 'excellon':
  4737. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  4738. self.init_code_editor(name=_("Source Editor"))
  4739. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  4740. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  4741. try:
  4742. for line in file:
  4743. proc_line = str(line).strip('\n')
  4744. self.ui.code_editor.append(proc_line)
  4745. except Exception as e:
  4746. log.debug('App.on_view_source() -->%s' % str(e))
  4747. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  4748. return
  4749. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4750. self.handleTextChanged()
  4751. self.ui.show()
  4752. def on_toggle_code_editor(self):
  4753. self.report_usage("on_toggle_code_editor()")
  4754. if self.toggle_codeeditor is False:
  4755. self.init_code_editor(name=_("Code Editor"))
  4756. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  4757. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  4758. else:
  4759. for idx in range(self.ui.plot_tab_area.count()):
  4760. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  4761. self.ui.plot_tab_area.closeTab(idx)
  4762. break
  4763. self.toggle_codeeditor = False
  4764. def on_filenewscript(self):
  4765. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  4766. self.init_code_editor(name=_("Script Editor"))
  4767. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  4768. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  4769. def on_fileopenscript(self):
  4770. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  4771. try:
  4772. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  4773. directory=self.get_last_folder(), filter=_filter_)
  4774. except TypeError:
  4775. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  4776. # The Qt methods above will return a QString which can cause problems later.
  4777. # So far json.dump() will fail to serialize it.
  4778. # TODO: Improve the serialization methods and remove this fix.
  4779. filename = str(filename)
  4780. if filename == "":
  4781. self.inform.emit(_("[WARNING_NOTCL]Open TCL script cancelled."))
  4782. else:
  4783. self.on_filenewscript()
  4784. try:
  4785. with open(filename, "r") as opened_script:
  4786. try:
  4787. for line in opened_script:
  4788. proc_line = str(line).strip('\n')
  4789. self.ui.code_editor.append(proc_line)
  4790. except Exception as e:
  4791. log.debug('App.on_fileopenscript() -->%s' % str(e))
  4792. self.inform.emit(_('[ERROR]App.on_fileopenscript() -->%s') % str(e))
  4793. return
  4794. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4795. self.handleTextChanged()
  4796. self.ui.show()
  4797. except Exception as e:
  4798. log.debug("App.on_fileopenscript() -> %s" % str(e))
  4799. def on_filerunscript(self, name=None):
  4800. """
  4801. File menu callback for loading and running a TCL script.
  4802. :return: None
  4803. """
  4804. self.report_usage("on_filerunscript")
  4805. App.log.debug("on_file_runscript()")
  4806. if name:
  4807. filename = name
  4808. else:
  4809. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  4810. try:
  4811. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  4812. directory=self.get_last_folder(), filter=_filter_)
  4813. except TypeError:
  4814. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  4815. # The Qt methods above will return a QString which can cause problems later.
  4816. # So far json.dump() will fail to serialize it.
  4817. # TODO: Improve the serialization methods and remove this fix.
  4818. filename = str(filename)
  4819. if filename == "":
  4820. self.inform.emit(_("[WARNING_NOTCL]Run TCL script cancelled."))
  4821. else:
  4822. try:
  4823. with open(filename, "r") as tcl_script:
  4824. cmd_line_shellfile_content = tcl_script.read()
  4825. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  4826. except Exception as e:
  4827. log.debug("App.on_filerunscript() -> %s" % str(e))
  4828. sys.exit(2)
  4829. def on_file_saveproject(self):
  4830. """
  4831. Callback for menu item File->Save Project. Saves the project to
  4832. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  4833. if set to None. The project is saved by calling ``self.save_project()``.
  4834. :return: None
  4835. """
  4836. self.report_usage("on_file_saveproject")
  4837. if self.project_filename is None:
  4838. self.on_file_saveprojectas()
  4839. else:
  4840. self.worker_task.emit({'fcn': self.save_project,
  4841. 'params': [self.project_filename]})
  4842. # self.save_project(self.project_filename)
  4843. self.file_opened.emit("project", self.project_filename)
  4844. self.file_saved.emit("project", self.project_filename)
  4845. self.should_we_save = False
  4846. def on_file_saveprojectas(self, make_copy=False, thread=True):
  4847. """
  4848. Callback for menu item File->Save Project As... Opens a file
  4849. chooser and saves the project to the given file via
  4850. ``self.save_project()``.
  4851. :return: None
  4852. """
  4853. self.report_usage("on_file_saveprojectas")
  4854. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  4855. try:
  4856. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4857. caption=_("Save Project As ..."),
  4858. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=str(self.date.replace('-', ''))),
  4859. filter=filter_)
  4860. except TypeError:
  4861. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  4862. filename = str(filename)
  4863. if filename == '':
  4864. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  4865. return
  4866. try:
  4867. f = open(filename, 'r')
  4868. f.close()
  4869. exists = True
  4870. except IOError:
  4871. exists = False
  4872. if thread is True:
  4873. self.worker_task.emit({'fcn': self.save_project,
  4874. 'params': [filename]})
  4875. else:
  4876. self.save_project(filename)
  4877. # self.save_project(filename)
  4878. self.file_opened.emit("project", filename)
  4879. self.file_saved.emit("project", filename)
  4880. if not make_copy:
  4881. self.project_filename = filename
  4882. self.should_we_save = False
  4883. def export_svg(self, obj_name, filename, scale_factor=0.00):
  4884. """
  4885. Exports a Geometry Object to an SVG file.
  4886. :param filename: Path to the SVG file to save to.
  4887. :return:
  4888. """
  4889. self.report_usage("export_svg()")
  4890. if filename is None:
  4891. filename = self.defaults["global_last_save_folder"]
  4892. self.log.debug("export_svg()")
  4893. try:
  4894. obj = self.collection.get_by_name(str(obj_name))
  4895. except:
  4896. # TODO: The return behavior has not been established... should raise exception?
  4897. return "Could not retrieve object: %s" % obj_name
  4898. with self.proc_container.new(_("Exporting SVG")) as proc:
  4899. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4900. # Determine bounding area for svg export
  4901. bounds = obj.bounds()
  4902. size = obj.size()
  4903. # Convert everything to strings for use in the xml doc
  4904. svgwidth = str(size[0])
  4905. svgheight = str(size[1])
  4906. minx = str(bounds[0])
  4907. miny = str(bounds[1] - size[1])
  4908. uom = obj.units.lower()
  4909. # Add a SVG Header and footer to the svg output from shapely
  4910. # The transform flips the Y Axis so that everything renders
  4911. # properly within svg apps such as inkscape
  4912. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4913. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4914. svg_header += 'width="' + svgwidth + uom + '" '
  4915. svg_header += 'height="' + svgheight + uom + '" '
  4916. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4917. svg_header += '<g transform="scale(1,-1)">'
  4918. svg_footer = '</g> </svg>'
  4919. svg_elem = svg_header + exported_svg + svg_footer
  4920. # Parse the xml through a xml parser just to add line feeds
  4921. # and to make it look more pretty for the output
  4922. svgcode = parse_xml_string(svg_elem)
  4923. with open(filename, 'w') as fp:
  4924. fp.write(svgcode.toprettyxml())
  4925. self.file_saved.emit("SVG", filename)
  4926. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  4927. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4928. """
  4929. Exports a Geometry Object to an SVG file in negative.
  4930. :param filename: Path to the SVG file to save to.
  4931. :param: use_thread: If True use threads
  4932. :type: Bool
  4933. :return:
  4934. """
  4935. self.report_usage("export_negative()")
  4936. if filename is None:
  4937. filename = self.defaults["global_last_save_folder"]
  4938. self.log.debug("export_svg() negative")
  4939. try:
  4940. obj = self.collection.get_by_name(str(obj_name))
  4941. except:
  4942. # TODO: The return behavior has not been established... should raise exception?
  4943. return "Could not retrieve object: %s" % obj_name
  4944. try:
  4945. box = self.collection.get_by_name(str(box_name))
  4946. except:
  4947. # TODO: The return behavior has not been established... should raise exception?
  4948. return "Could not retrieve object: %s" % box_name
  4949. if box is None:
  4950. self.inform.emit(_("[WARNING_NOTCL]No object Box. Using instead %s") % obj)
  4951. box = obj
  4952. def make_negative_film():
  4953. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4954. self.progress.emit(40)
  4955. # Determine bounding area for svg export
  4956. bounds = box.bounds()
  4957. size = box.size()
  4958. uom = obj.units.lower()
  4959. # Convert everything to strings for use in the xml doc
  4960. svgwidth = str(size[0] + (2 * boundary))
  4961. svgheight = str(size[1] + (2 * boundary))
  4962. minx = str(bounds[0] - boundary)
  4963. miny = str(bounds[1] + boundary + size[1])
  4964. miny_rect = str(bounds[1] - boundary)
  4965. # Add a SVG Header and footer to the svg output from shapely
  4966. # The transform flips the Y Axis so that everything renders
  4967. # properly within svg apps such as inkscape
  4968. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4969. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4970. svg_header += 'width="' + svgwidth + uom + '" '
  4971. svg_header += 'height="' + svgheight + uom + '" '
  4972. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4973. svg_header += '>'
  4974. svg_header += '<g transform="scale(1,-1)">'
  4975. svg_footer = '</g> </svg>'
  4976. self.progress.emit(60)
  4977. # Change the attributes of the exported SVG
  4978. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4979. # We set opacity to maximum
  4980. # We set the color to WHITE
  4981. root = ET.fromstring(exported_svg)
  4982. for child in root:
  4983. child.set('fill', '#FFFFFF')
  4984. child.set('opacity', '1.0')
  4985. child.set('stroke', '#FFFFFF')
  4986. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4987. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4988. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4989. first_svg_elem_tag = 'rect'
  4990. first_svg_elem_attribs = {
  4991. 'x': minx,
  4992. 'y': miny_rect,
  4993. 'width': svgwidth,
  4994. 'height': svgheight,
  4995. 'id': 'neg_rect',
  4996. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4997. }
  4998. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4999. exported_svg = ET.tostring(root)
  5000. svg_elem = svg_header + str(exported_svg) + svg_footer
  5001. self.progress.emit(80)
  5002. # Parse the xml through a xml parser just to add line feeds
  5003. # and to make it look more pretty for the output
  5004. doc = parse_xml_string(svg_elem)
  5005. with open(filename, 'w') as fp:
  5006. fp.write(doc.toprettyxml())
  5007. self.progress.emit(100)
  5008. self.file_saved.emit("SVG", filename)
  5009. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5010. if use_thread is True:
  5011. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5012. def job_thread_film(app_obj):
  5013. try:
  5014. make_negative_film()
  5015. except Exception as e:
  5016. proc.done()
  5017. return
  5018. proc.done()
  5019. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5020. else:
  5021. make_negative_film()
  5022. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  5023. """
  5024. Exports a Geometry Object to an SVG file in negative.
  5025. :param filename: Path to the SVG file to save to.
  5026. :param: use_thread: If True use threads
  5027. :type: Bool
  5028. :return:
  5029. """
  5030. self.report_usage("export_svg_black()")
  5031. if filename is None:
  5032. filename = self.defaults["global_last_save_folder"]
  5033. self.log.debug("export_svg() black")
  5034. try:
  5035. obj = self.collection.get_by_name(str(obj_name))
  5036. except:
  5037. # TODO: The return behavior has not been established... should raise exception?
  5038. return "Could not retrieve object: %s" % obj_name
  5039. try:
  5040. box = self.collection.get_by_name(str(box_name))
  5041. except:
  5042. # TODO: The return behavior has not been established... should raise exception?
  5043. return "Could not retrieve object: %s" % box_name
  5044. if box is None:
  5045. self.inform.emit(_("[WARNING_NOTCL]No object Box. Using instead %s") % obj)
  5046. box = obj
  5047. def make_black_film():
  5048. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5049. self.progress.emit(40)
  5050. # Change the attributes of the exported SVG
  5051. # We don't need stroke-width
  5052. # We set opacity to maximum
  5053. # We set the colour to WHITE
  5054. root = ET.fromstring(exported_svg)
  5055. for child in root:
  5056. child.set('fill', '#000000')
  5057. child.set('opacity', '1.0')
  5058. child.set('stroke', '#000000')
  5059. exported_svg = ET.tostring(root)
  5060. # Determine bounding area for svg export
  5061. bounds = box.bounds()
  5062. size = box.size()
  5063. # This contain the measure units
  5064. uom = obj.units.lower()
  5065. # Define a boundary around SVG of about 1.0mm (~39mils)
  5066. if uom in "mm":
  5067. boundary = 1.0
  5068. else:
  5069. boundary = 0.0393701
  5070. self.progress.emit(80)
  5071. # Convert everything to strings for use in the xml doc
  5072. svgwidth = str(size[0] + (2 * boundary))
  5073. svgheight = str(size[1] + (2 * boundary))
  5074. minx = str(bounds[0] - boundary)
  5075. miny = str(bounds[1] + boundary + size[1])
  5076. self.log.debug(minx)
  5077. self.log.debug(miny)
  5078. # Add a SVG Header and footer to the svg output from shapely
  5079. # The transform flips the Y Axis so that everything renders
  5080. # properly within svg apps such as inkscape
  5081. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5082. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5083. svg_header += 'width="' + svgwidth + uom + '" '
  5084. svg_header += 'height="' + svgheight + uom + '" '
  5085. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5086. svg_header += '>'
  5087. svg_header += '<g transform="scale(1,-1)">'
  5088. svg_footer = '</g> </svg>'
  5089. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  5090. self.progress.emit(90)
  5091. # Parse the xml through a xml parser just to add line feeds
  5092. # and to make it look more pretty for the output
  5093. doc = parse_xml_string(svg_elem)
  5094. with open(filename, 'w') as fp:
  5095. fp.write(doc.toprettyxml())
  5096. self.progress.emit(100)
  5097. self.file_saved.emit("SVG", filename)
  5098. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5099. if use_thread is True:
  5100. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5101. def job_thread_film(app_obj):
  5102. try:
  5103. make_black_film()
  5104. except Exception as e:
  5105. proc.done()
  5106. return
  5107. proc.done()
  5108. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5109. else:
  5110. make_black_film()
  5111. def save_source_file(self, obj_name, filename, use_thread=True):
  5112. """
  5113. Exports a Gerber Object to an Gerber file.
  5114. :param filename: Path to the Gerber file to save to.
  5115. :return:
  5116. """
  5117. self.report_usage("save source file()")
  5118. if filename is None:
  5119. filename = self.defaults["global_last_save_folder"]
  5120. self.log.debug("save source file()")
  5121. obj = self.collection.get_by_name(obj_name)
  5122. file_string = StringIO(obj.source_file)
  5123. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5124. with open(filename, 'w') as file:
  5125. file.writelines('G04*\n')
  5126. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  5127. (obj.kind.upper(), str(self.version), str(self.version_date)))
  5128. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  5129. file.writelines('G04 Created on : %s*\n' % time_string)
  5130. for line in file_string:
  5131. file.writelines(line)
  5132. def export_excellon(self, obj_name, filename, use_thread=True):
  5133. """
  5134. Exports a Excellon Object to an Excellon file.
  5135. :param filename: Path to the Excellon file to save to.
  5136. :return:
  5137. """
  5138. self.report_usage("export_excellon()")
  5139. if filename is None:
  5140. filename = self.defaults["global_last_save_folder"]
  5141. self.log.debug("export_excellon()")
  5142. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  5143. self.defaults["excellon_exp_decimals"]
  5144. )
  5145. units = ''
  5146. try:
  5147. obj = self.collection.get_by_name(str(obj_name))
  5148. except:
  5149. # TODO: The return behavior has not been established... should raise exception?
  5150. return "Could not retrieve object: %s" % obj_name
  5151. # updated units
  5152. eunits = self.defaults["excellon_exp_units"]
  5153. ewhole = self.defaults["excellon_exp_integer"]
  5154. efract = self.defaults["excellon_exp_decimals"]
  5155. ezeros = self.defaults["excellon_exp_zeros"]
  5156. eformat = self.defaults[ "excellon_exp_format"]
  5157. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5158. if fc_units == 'MM':
  5159. factor = 1 if eunits == 'METRIC' else 0.03937
  5160. else:
  5161. factor = 25.4 if eunits == 'METRIC' else 1
  5162. def make_excellon():
  5163. try:
  5164. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5165. header = 'M48\n'
  5166. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5167. (str(self.version), str(self.version_date))
  5168. header += ';Filename: %s' % str(obj_name) + '\n'
  5169. header += ';Created on : %s' % time_str + '\n'
  5170. if eformat == 'dec':
  5171. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  5172. header += eunits + '\n'
  5173. for tool in obj.tools:
  5174. if eunits == 'METRIC':
  5175. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5176. tool=str(tool),
  5177. dec=2)
  5178. else:
  5179. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5180. tool=str(tool),
  5181. dec=4)
  5182. else:
  5183. if ezeros == 'LZ':
  5184. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5185. form='ndec', e_zeros='LZ', factor=factor)
  5186. header += '%s,%s\n' % (eunits, 'LZ')
  5187. header += format_exc
  5188. for tool in obj.tools:
  5189. if eunits == 'METRIC':
  5190. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5191. tool=str(tool),
  5192. dec=2)
  5193. else:
  5194. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5195. tool=str(tool),
  5196. dec=4)
  5197. else:
  5198. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5199. form='ndec', e_zeros='TZ', factor=factor)
  5200. header += '%s,%s\n' % (eunits, 'TZ')
  5201. header += format_exc
  5202. for tool in obj.tools:
  5203. if eunits == 'METRIC':
  5204. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5205. tool=str(tool),
  5206. dec=2)
  5207. else:
  5208. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5209. tool=str(tool),
  5210. dec=4)
  5211. header += '%\n'
  5212. footer = 'M30\n'
  5213. exported_excellon = header
  5214. exported_excellon += excellon_code
  5215. exported_excellon += footer
  5216. with open(filename, 'w') as fp:
  5217. fp.write(exported_excellon)
  5218. self.file_saved.emit("Excellon", filename)
  5219. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  5220. except Exception as e:
  5221. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  5222. return 'fail'
  5223. if use_thread is True:
  5224. with self.proc_container.new(_("Exporting Excellon")) as proc:
  5225. def job_thread_exc(app_obj):
  5226. ret = make_excellon()
  5227. if ret == 'fail':
  5228. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5229. return
  5230. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5231. else:
  5232. ret = make_excellon()
  5233. if ret == 'fail':
  5234. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5235. return
  5236. def export_dxf(self, obj_name, filename, use_thread=True):
  5237. """
  5238. Exports a Geometry Object to an DXF file.
  5239. :param filename: Path to the DXF file to save to.
  5240. :return:
  5241. """
  5242. self.report_usage("export_dxf()")
  5243. if filename is None:
  5244. filename = self.defaults["global_last_save_folder"]
  5245. self.log.debug("export_dxf()")
  5246. format_exc = ''
  5247. units = ''
  5248. try:
  5249. obj = self.collection.get_by_name(str(obj_name))
  5250. except:
  5251. # TODO: The return behavior has not been established... should raise exception?
  5252. return "Could not retrieve object: %s" % obj_name
  5253. # updated units
  5254. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5255. if units == 'IN' or units == 'INCH':
  5256. units = 'INCH'
  5257. elif units == 'MM' or units == 'METIRC':
  5258. units ='METRIC'
  5259. def make_dxf():
  5260. try:
  5261. dxf_code = obj.export_dxf()
  5262. dxf_code.saveas(filename)
  5263. self.file_saved.emit("DXF", filename)
  5264. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  5265. except:
  5266. return 'fail'
  5267. if use_thread is True:
  5268. with self.proc_container.new(_("Exporting DXF")) as proc:
  5269. def job_thread_exc(app_obj):
  5270. ret = make_dxf()
  5271. if ret == 'fail':
  5272. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  5273. return
  5274. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5275. else:
  5276. ret = make_dxf()
  5277. if ret == 'fail':
  5278. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  5279. return
  5280. def import_svg(self, filename, geo_type='geometry', outname=None):
  5281. """
  5282. Adds a new Geometry Object to the projects and populates
  5283. it with shapes extracted from the SVG file.
  5284. :param filename: Path to the SVG file.
  5285. :param outname:
  5286. :return:
  5287. """
  5288. self.report_usage("import_svg()")
  5289. obj_type = ""
  5290. if geo_type is None or geo_type == "geometry":
  5291. obj_type = "geometry"
  5292. elif geo_type == "gerber":
  5293. obj_type = geo_type
  5294. else:
  5295. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5296. "Only Geometry and Gerber are supported"))
  5297. return
  5298. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5299. def obj_init(geo_obj, app_obj):
  5300. geo_obj.import_svg(filename, obj_type, units=units)
  5301. geo_obj.multigeo = False
  5302. with self.proc_container.new(_("Importing SVG")) as proc:
  5303. # Object name
  5304. name = outname or filename.split('/')[-1].split('\\')[-1]
  5305. self.new_object(obj_type, name, obj_init, autoselected=False)
  5306. self.progress.emit(20)
  5307. # Register recent file
  5308. self.file_opened.emit("svg", filename)
  5309. # GUI feedback
  5310. self.inform.emit(_("[success] Opened: %s") % filename)
  5311. self.progress.emit(100)
  5312. def import_dxf(self, filename, geo_type='geometry', outname=None):
  5313. """
  5314. Adds a new Geometry Object to the projects and populates
  5315. it with shapes extracted from the DXF file.
  5316. :param filename: Path to the DXF file.
  5317. :param outname:
  5318. :type putname: str
  5319. :return:
  5320. """
  5321. self.report_usage("import_dxf()")
  5322. obj_type = ""
  5323. if geo_type is None or geo_type == "geometry":
  5324. obj_type = "geometry"
  5325. elif geo_type == "gerber":
  5326. obj_type = geo_type
  5327. else:
  5328. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5329. "Only Geometry and Gerber are supported"))
  5330. return
  5331. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5332. def obj_init(geo_obj, app_obj):
  5333. geo_obj.import_dxf(filename, obj_type, units=units)
  5334. geo_obj.multigeo = False
  5335. with self.proc_container.new(_("Importing DXF")) as proc:
  5336. # Object name
  5337. name = outname or filename.split('/')[-1].split('\\')[-1]
  5338. self.new_object(obj_type, name, obj_init, autoselected=False)
  5339. self.progress.emit(20)
  5340. # Register recent file
  5341. self.file_opened.emit("dxf", filename)
  5342. # GUI feedback
  5343. self.inform.emit(_("[success] Opened: %s") % filename)
  5344. self.progress.emit(100)
  5345. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  5346. """
  5347. Adds a new Geometry Object to the projects and populates
  5348. it with shapes extracted from the SVG file.
  5349. :param filename: Path to the SVG file.
  5350. :param outname:
  5351. :return:
  5352. """
  5353. self.report_usage("import_image()")
  5354. obj_type = ""
  5355. if type is None or type == "geometry":
  5356. obj_type = "geometry"
  5357. elif type == "gerber":
  5358. obj_type = type
  5359. else:
  5360. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5361. "Only Geometry and Gerber are supported"))
  5362. return
  5363. def obj_init(geo_obj, app_obj):
  5364. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  5365. geo_obj.multigeo = False
  5366. with self.proc_container.new(_("Importing Image")) as proc:
  5367. # Object name
  5368. name = outname or filename.split('/')[-1].split('\\')[-1]
  5369. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  5370. self.new_object(obj_type, name, obj_init)
  5371. self.progress.emit(20)
  5372. # Register recent file
  5373. self.file_opened.emit("image", filename)
  5374. # GUI feedback
  5375. self.inform.emit(_("[success] Opened: %s") % filename)
  5376. self.progress.emit(100)
  5377. def open_gerber(self, filename, outname=None):
  5378. """
  5379. Opens a Gerber file, parses it and creates a new object for
  5380. it in the program. Thread-safe.
  5381. :param outname: Name of the resulting object. None causes the
  5382. name to be that of the file.
  5383. :param filename: Gerber file filename
  5384. :type filename: str
  5385. :param follow: If true, the parser will not create polygons, just lines
  5386. following the gerber path.
  5387. :type follow: bool
  5388. :return: None
  5389. """
  5390. # How the object should be initialized
  5391. def obj_init(gerber_obj, app_obj):
  5392. assert isinstance(gerber_obj, FlatCAMGerber), \
  5393. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  5394. # Opening the file happens here
  5395. self.progress.emit(30)
  5396. try:
  5397. gerber_obj.parse_file(filename)
  5398. except IOError:
  5399. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  5400. app_obj.progress.emit(0)
  5401. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  5402. return "fail"
  5403. except ParseError as err:
  5404. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: {name}. {error}").format(name=filename, error=str(err)))
  5405. app_obj.progress.emit(0)
  5406. self.log.error(str(err))
  5407. return "fail"
  5408. except:
  5409. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  5410. msg += traceback.format_exc()
  5411. app_obj.inform.emit(msg)
  5412. return "fail"
  5413. if gerber_obj.is_empty():
  5414. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  5415. # self.collection.set_active(gerber_obj.options["name"])
  5416. # self.collection.delete_active()
  5417. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  5418. return "fail"
  5419. # Further parsing
  5420. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  5421. App.log.debug("open_gerber()")
  5422. with self.proc_container.new(_("Opening Gerber")) as proc:
  5423. self.progress.emit(10)
  5424. # Object name
  5425. name = outname or filename.split('/')[-1].split('\\')[-1]
  5426. ### Object creation ###
  5427. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  5428. if ret == 'fail':
  5429. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  5430. return
  5431. # Register recent file
  5432. self.file_opened.emit("gerber", filename)
  5433. self.progress.emit(100)
  5434. # GUI feedback
  5435. self.inform.emit(_("[success] Opened: %s") % filename)
  5436. def open_excellon(self, filename, outname=None):
  5437. """
  5438. Opens an Excellon file, parses it and creates a new object for
  5439. it in the program. Thread-safe.
  5440. :param outname: Name of the resulting object. None causes the
  5441. name to be that of the file.
  5442. :param filename: Excellon file filename
  5443. :type filename: str
  5444. :return: None
  5445. """
  5446. App.log.debug("open_excellon()")
  5447. #self.progress.emit(10)
  5448. # How the object should be initialized
  5449. def obj_init(excellon_obj, app_obj):
  5450. # self.progress.emit(20)
  5451. try:
  5452. ret = excellon_obj.parse_file(filename)
  5453. if ret == "fail":
  5454. log.debug("Excellon parsing failed.")
  5455. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  5456. return "fail"
  5457. except IOError:
  5458. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  5459. log.debug("Could not open Excellon object.")
  5460. self.progress.emit(0) # TODO: self and app_bjj mixed
  5461. return "fail"
  5462. except:
  5463. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  5464. msg += traceback.format_exc()
  5465. app_obj.inform.emit(msg)
  5466. return "fail"
  5467. ret = excellon_obj.create_geometry()
  5468. if ret == 'fail':
  5469. log.debug("Could not create geometry for Excellon object.")
  5470. return "fail"
  5471. # if excellon_obj.is_empty():
  5472. # app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  5473. # return "fail"
  5474. for tool in excellon_obj.tools:
  5475. if excellon_obj.tools[tool]['solid_geometry']:
  5476. return
  5477. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  5478. return "fail"
  5479. with self.proc_container.new(_("Opening Excellon.")):
  5480. # Object name
  5481. name = outname or filename.split('/')[-1].split('\\')[-1]
  5482. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  5483. if ret == 'fail':
  5484. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  5485. return
  5486. # Register recent file
  5487. self.file_opened.emit("excellon", filename)
  5488. # GUI feedback
  5489. self.inform.emit(_("[success] Opened: %s") % filename)
  5490. # self.progress.emit(100)
  5491. def open_gcode(self, filename, outname=None):
  5492. """
  5493. Opens a G-gcode file, parses it and creates a new object for
  5494. it in the program. Thread-safe.
  5495. :param outname: Name of the resulting object. None causes the
  5496. name to be that of the file.
  5497. :param filename: G-code file filename
  5498. :type filename: str
  5499. :return: None
  5500. """
  5501. App.log.debug("open_gcode()")
  5502. # How the object should be initialized
  5503. def obj_init(job_obj, app_obj_):
  5504. """
  5505. :type app_obj_: App
  5506. """
  5507. assert isinstance(app_obj_, App), \
  5508. "Initializer expected App, got %s" % type(app_obj_)
  5509. self.progress.emit(10)
  5510. try:
  5511. f = open(filename)
  5512. gcode = f.read()
  5513. f.close()
  5514. except IOError:
  5515. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  5516. self.progress.emit(0)
  5517. return "fail"
  5518. job_obj.gcode = gcode
  5519. self.progress.emit(20)
  5520. ret = job_obj.gcode_parse()
  5521. if ret == "fail":
  5522. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  5523. return "fail"
  5524. self.progress.emit(60)
  5525. job_obj.create_geometry()
  5526. with self.proc_container.new(_("Opening G-Code.")):
  5527. # Object name
  5528. name = outname or filename.split('/')[-1].split('\\')[-1]
  5529. # New object creation and file processing
  5530. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  5531. if ret == 'fail':
  5532. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  5533. "Attempting to create a FlatCAM CNCJob Object from "
  5534. "G-Code file failed during processing"))
  5535. return "fail"
  5536. # Register recent file
  5537. self.file_opened.emit("cncjob", filename)
  5538. # GUI feedback
  5539. self.inform.emit(_("[success] Opened: %s") % filename)
  5540. self.progress.emit(100)
  5541. def open_config_file(self, filename, run_from_arg=None):
  5542. """
  5543. Loads a config file from the specified file.
  5544. :param filename: Name of the file from which to load.
  5545. :type filename: str
  5546. :return: None
  5547. """
  5548. App.log.debug("Opening config file: " + filename)
  5549. # add the tab if it was closed
  5550. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  5551. # first clear previous text in text editor (if any)
  5552. self.ui.code_editor.clear()
  5553. # Switch plot_area to CNCJob tab
  5554. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5555. try:
  5556. if filename:
  5557. f = QtCore.QFile(filename)
  5558. if f.open(QtCore.QIODevice.ReadOnly):
  5559. stream = QtCore.QTextStream(f)
  5560. gcode_edited = stream.readAll()
  5561. self.ui.code_editor.setPlainText(gcode_edited)
  5562. f.close()
  5563. except IOError:
  5564. App.log.error("Failed to open config file: %s" % filename)
  5565. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  5566. return
  5567. def open_project(self, filename, run_from_arg=None):
  5568. """
  5569. Loads a project from the specified file.
  5570. 1) Loads and parses file
  5571. 2) Registers the file as recently opened.
  5572. 3) Calls on_file_new()
  5573. 4) Updates options
  5574. 5) Calls new_object() with the object's from_dict() as init method.
  5575. 6) Calls plot_all()
  5576. :param filename: Name of the file from which to load.
  5577. :type filename: str
  5578. :return: None
  5579. """
  5580. App.log.debug("Opening project: " + filename)
  5581. # Open and parse an uncompressed Project file
  5582. try:
  5583. f = open(filename, 'r')
  5584. except IOError:
  5585. App.log.error("Failed to open project file: %s" % filename)
  5586. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  5587. return
  5588. try:
  5589. d = json.load(f, object_hook=dict2obj)
  5590. except:
  5591. App.log.error("Failed to parse project file: %s" % filename)
  5592. self.inform.emit(_("[ERROR_NOTCL] Failed to parse project file: %s") % filename)
  5593. f.close()
  5594. # Open and parse a compressed Project file
  5595. try:
  5596. with lzma.open(filename) as f:
  5597. file_content = f.read().decode('utf-8')
  5598. d = json.loads(file_content, object_hook=dict2obj)
  5599. except IOError:
  5600. App.log.error("Failed to open project file: %s" % filename)
  5601. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  5602. return
  5603. self.file_opened.emit("project", filename)
  5604. # Clear the current project
  5605. ## NOT THREAD SAFE ##
  5606. if run_from_arg is True:
  5607. pass
  5608. else:
  5609. self.on_file_new()
  5610. #Project options
  5611. self.options.update(d['options'])
  5612. self.project_filename = filename
  5613. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  5614. self.set_screen_units(self.options["units"])
  5615. # Re create objects
  5616. App.log.debug("Re-creating objects...")
  5617. for obj in d['objs']:
  5618. def obj_init(obj_inst, app_inst):
  5619. obj_inst.from_dict(obj)
  5620. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  5621. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  5622. self.plot_all()
  5623. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  5624. self.should_we_save = False
  5625. App.log.debug("Project loaded")
  5626. def propagate_defaults(self, silent=False):
  5627. """
  5628. This method is used to set default values in classes. It's
  5629. an alternative to project options but allows the use
  5630. of values invisible to the user.
  5631. :return: None
  5632. """
  5633. if silent is False:
  5634. self.log.debug("propagate_defaults()")
  5635. # Which objects to update the given parameters.
  5636. routes = {
  5637. "global_zdownrate": CNCjob,
  5638. "excellon_zeros": Excellon,
  5639. "excellon_format_upper_in": Excellon,
  5640. "excellon_format_lower_in": Excellon,
  5641. "excellon_format_upper_mm": Excellon,
  5642. "excellon_format_lower_mm": Excellon,
  5643. "excellon_units": Excellon,
  5644. "gerber_use_buffer_for_union": Gerber,
  5645. "geometry_multidepth": Geometry
  5646. }
  5647. for param in routes:
  5648. if param in routes[param].defaults:
  5649. try:
  5650. routes[param].defaults[param] = self.defaults[param]
  5651. if silent is False:
  5652. self.log.debug(" " + param + " OK")
  5653. except KeyError:
  5654. if silent is False:
  5655. self.log.debug(" ERROR: " + param + " not in defaults.")
  5656. else:
  5657. # Try extracting the name:
  5658. # classname_param here is param in the object
  5659. if param.find(routes[param].__name__.lower() + "_") == 0:
  5660. p = param[len(routes[param].__name__) + 1:]
  5661. if p in routes[param].defaults:
  5662. routes[param].defaults[p] = self.defaults[param]
  5663. if silent is False:
  5664. self.log.debug(" " + param + " OK!")
  5665. def restore_main_win_geom(self):
  5666. try:
  5667. self.ui.setGeometry(self.defaults["global_def_win_x"],
  5668. self.defaults["global_def_win_y"],
  5669. self.defaults["global_def_win_w"],
  5670. self.defaults["global_def_win_h"])
  5671. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  5672. settings = QSettings("Open Source", "FlatCAM")
  5673. if settings.contains("maximized_gui"):
  5674. maximized_ui = settings.value('maximized_gui', type=bool)
  5675. if maximized_ui is True:
  5676. self.ui.showMaximized()
  5677. except KeyError:
  5678. pass
  5679. def plot_all(self, zoom=True):
  5680. """
  5681. Re-generates all plots from all objects.
  5682. :return: None
  5683. """
  5684. self.log.debug("Plot_all()")
  5685. for obj in self.collection.get_list():
  5686. def worker_task(obj):
  5687. with self.proc_container.new("Plotting"):
  5688. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5689. if zoom:
  5690. self.object_plotted.emit(obj)
  5691. # Send to worker
  5692. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  5693. # self.progress.emit(10)
  5694. #
  5695. # def worker_task(app_obj):
  5696. # print "worker task"
  5697. # percentage = 0.1
  5698. # try:
  5699. # delta = 0.9 / len(self.collection.get_list())
  5700. # except ZeroDivisionError:
  5701. # self.progress.emit(0)
  5702. # return
  5703. # for obj in self.collection.get_list():
  5704. # with self.proc_container.new("Plotting"):
  5705. # obj.plot()
  5706. # app_obj.object_plotted.emit(obj)
  5707. #
  5708. # percentage += delta
  5709. # self.progress.emit(int(percentage*100))
  5710. #
  5711. # self.progress.emit(0)
  5712. # self.plots_updated.emit()
  5713. #
  5714. # # Send to worker
  5715. # #self.worker.add_task(worker_task, [self])
  5716. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5717. def register_folder(self, filename):
  5718. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5719. def register_save_folder(self, filename):
  5720. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5721. def set_progress_bar(self, percentage, text=""):
  5722. self.ui.progress_bar.setValue(int(percentage))
  5723. def setup_shell(self):
  5724. """
  5725. Creates shell functions. Runs once at startup.
  5726. :return: None
  5727. """
  5728. self.log.debug("setup_shell()")
  5729. def shelp(p=None):
  5730. if not p:
  5731. return _("Available commands:\n") + \
  5732. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  5733. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  5734. if p not in commands:
  5735. return "Unknown command: %s" % p
  5736. return commands[p]["help"]
  5737. # --- Migrated to new architecture ---
  5738. # def options(name):
  5739. # ops = self.collection.get_by_name(str(name)).options
  5740. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  5741. def h(*args):
  5742. """
  5743. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  5744. and standalone parameters into list.
  5745. """
  5746. kwa = {}
  5747. a = []
  5748. n = len(args)
  5749. name = None
  5750. for i in range(n):
  5751. match = re.search(r'^-([a-zA-Z].*)', args[i])
  5752. if match:
  5753. assert name is None
  5754. name = match.group(1)
  5755. continue
  5756. if name is None:
  5757. a.append(args[i])
  5758. else:
  5759. kwa[name] = args[i]
  5760. name = None
  5761. return a, kwa
  5762. @contextmanager
  5763. def wait_signal(signal, timeout=10000):
  5764. """
  5765. Block loop until signal emitted, timeout (ms) elapses
  5766. or unhandled exception happens in a thread.
  5767. :param signal: Signal to wait for.
  5768. """
  5769. loop = QtCore.QEventLoop()
  5770. # Normal termination
  5771. signal.connect(loop.quit)
  5772. # Termination by exception in thread
  5773. self.thread_exception.connect(loop.quit)
  5774. status = {'timed_out': False}
  5775. def report_quit():
  5776. status['timed_out'] = True
  5777. loop.quit()
  5778. yield
  5779. # Temporarily change how exceptions are managed.
  5780. oeh = sys.excepthook
  5781. ex = []
  5782. def except_hook(type_, value, traceback_):
  5783. ex.append(value)
  5784. oeh(type_, value, traceback_)
  5785. sys.excepthook = except_hook
  5786. # Terminate on timeout
  5787. if timeout is not None:
  5788. QtCore.QTimer.singleShot(timeout, report_quit)
  5789. #### Block ####
  5790. loop.exec_()
  5791. # Restore exception management
  5792. sys.excepthook = oeh
  5793. if ex:
  5794. self.raiseTclError(str(ex[0]))
  5795. if status['timed_out']:
  5796. raise Exception('Timed out!')
  5797. def make_docs():
  5798. output = ''
  5799. import collections
  5800. od = collections.OrderedDict(sorted(commands.items()))
  5801. for cmd_, val in od.items():
  5802. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  5803. t = val['help']
  5804. usage_i = t.find('>')
  5805. if usage_i < 0:
  5806. expl = t
  5807. output += expl + '\n\n'
  5808. continue
  5809. expl = t[:usage_i - 1]
  5810. output += expl + '\n\n'
  5811. end_usage_i = t[usage_i:].find('\n')
  5812. if end_usage_i < 0:
  5813. end_usage_i = len(t[usage_i:])
  5814. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  5815. else:
  5816. extras = t[usage_i+end_usage_i+1:]
  5817. parts = [s.strip() for s in extras.split('\n')]
  5818. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  5819. for p in parts:
  5820. output += ' ' + p + '\n\n'
  5821. return output
  5822. '''
  5823. Howto implement TCL shell commands:
  5824. All parameters passed to command should be possible to set as None and test it afterwards.
  5825. This is because we need to see error caused in tcl,
  5826. if None value as default parameter is not allowed TCL will return empty error.
  5827. Use:
  5828. def mycommand(name=None,...):
  5829. Test it like this:
  5830. if name is None:
  5831. self.raise_tcl_error('Argument name is missing.')
  5832. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  5833. otherwise we will miss it and processing will silently continue.
  5834. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  5835. which is catched in exec_command and displayed in TCL shell console with red background.
  5836. Error in console is displayed with TCL trace.
  5837. This behavior works only within main thread,
  5838. errors with promissed tasks can be catched and detected only with log.
  5839. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  5840. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  5841. '''
  5842. commands = {
  5843. 'help': {
  5844. 'fcn': shelp,
  5845. 'help': _("Shows list of commands.")
  5846. },
  5847. }
  5848. # Import/overwrite tcl commands as objects of TclCommand descendants
  5849. # This modifies the variable 'commands'.
  5850. tclCommands.register_all_commands(self, commands)
  5851. # Add commands to the tcl interpreter
  5852. for cmd in commands:
  5853. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  5854. # Make the tcl puts function return instead of print to stdout
  5855. self.tcl.eval('''
  5856. rename puts original_puts
  5857. proc puts {args} {
  5858. if {[llength $args] == 1} {
  5859. return "[lindex $args 0]"
  5860. } else {
  5861. eval original_puts $args
  5862. }
  5863. }
  5864. ''')
  5865. def setup_recent_items(self):
  5866. # TODO: Move this to constructor
  5867. icons = {
  5868. "gerber": "share/flatcam_icon16.png",
  5869. "excellon": "share/drill16.png",
  5870. "cncjob": "share/cnc16.png",
  5871. "project": "share/project16.png",
  5872. "svg": "share/geometry16.png",
  5873. "dxf": "share/dxf16.png",
  5874. "image": "share/image16.png"
  5875. }
  5876. openers = {
  5877. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  5878. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  5879. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  5880. 'project': self.open_project,
  5881. 'svg': self.import_svg,
  5882. 'dxf': self.import_dxf,
  5883. 'image': self.import_image
  5884. }
  5885. # Open file
  5886. try:
  5887. f = open(self.data_path + '/recent.json')
  5888. except IOError:
  5889. App.log.error("Failed to load recent item list.")
  5890. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  5891. return
  5892. try:
  5893. self.recent = json.load(f)
  5894. except json.scanner.JSONDecodeError:
  5895. App.log.error("Failed to parse recent item list.")
  5896. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  5897. f.close()
  5898. return
  5899. f.close()
  5900. # Closure needed to create callbacks in a loop.
  5901. # Otherwise late binding occurs.
  5902. def make_callback(func, fname):
  5903. def opener():
  5904. func(fname)
  5905. return opener
  5906. def reset_recent():
  5907. # Reset menu
  5908. self.ui.recent.clear()
  5909. self.recent = []
  5910. try:
  5911. f = open(self.data_path + '/recent.json', 'w')
  5912. except IOError:
  5913. App.log.error("Failed to open recent items file for writing.")
  5914. return
  5915. json.dump(self.recent, f)
  5916. # Reset menu
  5917. self.ui.recent.clear()
  5918. # Create menu items
  5919. for recent in self.recent:
  5920. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5921. try:
  5922. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5923. # Attach callback
  5924. o = make_callback(openers[recent["kind"]], recent['filename'])
  5925. action.triggered.connect(o)
  5926. self.ui.recent.addAction(action)
  5927. except KeyError:
  5928. App.log.error("Unsupported file type: %s" % recent["kind"])
  5929. # Last action in Recent Files menu is one that Clear the content
  5930. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  5931. clear_action.triggered.connect(reset_recent)
  5932. self.ui.recent.addSeparator()
  5933. self.ui.recent.addAction(clear_action)
  5934. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5935. # self.ui.menufilerecent.set_submenu(recent_menu)
  5936. # recent_menu.show_all()
  5937. # self.ui.recent.show()
  5938. self.log.debug("Recent items list has been populated.")
  5939. def setup_component_editor(self):
  5940. # label = QtWidgets.QLabel("Choose an item from Project")
  5941. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5942. sel_title = QtWidgets.QTextEdit(
  5943. _('<b>Shortcut Key List</b>'))
  5944. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5945. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5946. # font = self.sel_title.font()
  5947. # font.setPointSize(12)
  5948. # self.sel_title.setFont(font)
  5949. selected_text = _('''
  5950. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  5951. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5952. The normal flow when working in FlatCAM is the following:</span></p>
  5953. <ol>
  5954. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  5955. <br />
  5956. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  5957. &nbsp;</li>
  5958. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  5959. <br />
  5960. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  5961. <br />
  5962. You can change the parameters in this screen and the flow direction is like this:<br />
  5963. <br />
  5964. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  5965. </ol>
  5966. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  5967. ''')
  5968. sel_title.setText(selected_text)
  5969. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5970. self.ui.selected_scroll_area.setWidget(sel_title)
  5971. # tool_title = QtWidgets.QTextEdit(
  5972. # '<b>Shortcut Key List</b>')
  5973. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5974. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5975. # # font = self.sel_title.font()
  5976. # # font.setPointSize(12)
  5977. # # self.sel_title.setFont(font)
  5978. #
  5979. # tool_text = '''
  5980. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  5981. #
  5982. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5983. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  5984. #
  5985. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  5986. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  5987. #
  5988. # <ol>
  5989. # </ol>
  5990. #
  5991. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  5992. #
  5993. # '''
  5994. #
  5995. # tool_title.setText(tool_text)
  5996. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5997. #
  5998. # self.ui.tool_scroll_area.setWidget(tool_title)
  5999. def setup_obj_classes(self):
  6000. """
  6001. Sets up application specifics on the FlatCAMObj class.
  6002. :return: None
  6003. """
  6004. FlatCAMObj.app = self
  6005. ObjectCollection.app = self
  6006. FCProcess.app = self
  6007. FCProcessContainer.app = self
  6008. def version_check(self):
  6009. """
  6010. Checks for the latest version of the program. Alerts the
  6011. user if theirs is outdated. This method is meant to be run
  6012. in a separate thread.
  6013. :return: None
  6014. """
  6015. self.log.debug("version_check()")
  6016. if self.ui.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  6017. full_url = App.version_url + \
  6018. "?s=" + str(self.defaults['global_serial']) + \
  6019. "&v=" + str(self.version) + \
  6020. "&os=" + str(self.os) + \
  6021. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  6022. else:
  6023. # no_stats dict; just so it won't break things on website
  6024. no_ststs_dict = {}
  6025. no_ststs_dict["global_ststs"] = {}
  6026. full_url = App.version_url + \
  6027. "?s=" + str(self.defaults['global_serial']) + \
  6028. "&v=" + str(self.version) + \
  6029. "&os=" + str(self.os) + \
  6030. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6031. App.log.debug("Checking for updates @ %s" % full_url)
  6032. ### Get the data
  6033. try:
  6034. f = urllib.request.urlopen(full_url)
  6035. except:
  6036. # App.log.warning("Failed checking for latest version. Could not connect.")
  6037. self.log.warning("Failed checking for latest version. Could not connect.")
  6038. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  6039. return
  6040. try:
  6041. data = json.load(f)
  6042. except Exception as e:
  6043. App.log.error("Could not parse information about latest version.")
  6044. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  6045. App.log.debug("json.load(): %s" % str(e))
  6046. f.close()
  6047. return
  6048. f.close()
  6049. ### Latest version?
  6050. if self.version >= data["version"]:
  6051. App.log.debug("FlatCAM is up to date!")
  6052. self.inform.emit(_("[success] FlatCAM is up to date!"))
  6053. return
  6054. App.log.debug("Newer version available.")
  6055. self.message.emit(
  6056. _("Newer Version Available"),
  6057. _("There is a newer version of FlatCAM available for download:\n\n") +
  6058. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  6059. _("info")
  6060. )
  6061. def on_zoom_fit(self, event):
  6062. """
  6063. Callback for zoom-out request. This can be either from the corresponding
  6064. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6065. with axes limits from the geometry bounds of all objects.
  6066. :param event: Ignored.
  6067. :return: None
  6068. """
  6069. self.plotcanvas.fit_view()
  6070. def disable_all_plots(self):
  6071. self.report_usage("disable_all_plots()")
  6072. self.disable_plots(self.collection.get_list())
  6073. self.inform.emit(_("[success]All plots disabled."))
  6074. def disable_other_plots(self):
  6075. self.report_usage("disable_other_plots()")
  6076. self.disable_plots(self.collection.get_non_selected())
  6077. self.inform.emit(_("[success]All non selected plots disabled."))
  6078. def enable_all_plots(self):
  6079. self.report_usage("enable_all_plots()")
  6080. self.enable_plots(self.collection.get_list())
  6081. self.inform.emit(_("[success]All plots enabled."))
  6082. # TODO: FIX THIS
  6083. '''
  6084. By default this is not threaded
  6085. If threaded the app give warnings like this:
  6086. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6087. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6088. '''
  6089. def enable_plots(self, objects, threaded=False):
  6090. if threaded is True:
  6091. def worker_task(app_obj):
  6092. percentage = 0.1
  6093. try:
  6094. delta = 0.9 / len(objects)
  6095. except ZeroDivisionError:
  6096. self.progress.emit(0)
  6097. return
  6098. for obj in objects:
  6099. obj.options['plot'] = True
  6100. percentage += delta
  6101. self.progress.emit(int(percentage*100))
  6102. self.progress.emit(0)
  6103. self.plots_updated.emit()
  6104. self.collection.update_view()
  6105. # Send to worker
  6106. # self.worker.add_task(worker_task, [self])
  6107. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6108. else:
  6109. for obj in objects:
  6110. obj.options['plot'] = True
  6111. self.progress.emit(0)
  6112. self.plots_updated.emit()
  6113. self.collection.update_view()
  6114. # TODO: FIX THIS
  6115. '''
  6116. By default this is not threaded
  6117. If threaded the app give warnings like this:
  6118. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6119. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6120. '''
  6121. def disable_plots(self, objects, threaded=False):
  6122. # TODO: This method is very similar to replot_all. Try to merge.
  6123. """
  6124. Disables plots
  6125. :param objects: list
  6126. Objects to be disabled
  6127. :return:
  6128. """
  6129. if threaded is True:
  6130. self.progress.emit(10)
  6131. def worker_task(app_obj):
  6132. percentage = 0.1
  6133. try:
  6134. delta = 0.9 / len(objects)
  6135. except ZeroDivisionError:
  6136. self.progress.emit(0)
  6137. return
  6138. for obj in objects:
  6139. obj.options['plot'] = False
  6140. percentage += delta
  6141. self.progress.emit(int(percentage*100))
  6142. self.progress.emit(0)
  6143. self.plots_updated.emit()
  6144. self.collection.update_view()
  6145. # Send to worker
  6146. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6147. else:
  6148. for obj in objects:
  6149. obj.options['plot'] = False
  6150. self.plots_updated.emit()
  6151. self.collection.update_view()
  6152. def clear_plots(self):
  6153. objects = self.collection.get_list()
  6154. for obj in objects:
  6155. obj.clear(obj == objects[-1])
  6156. # Clear pool to free memory
  6157. self.clear_pool()
  6158. def generate_cnc_job(self, objects):
  6159. self.report_usage("generate_cnc_job()")
  6160. # for obj in objects:
  6161. # obj.generatecncjob()
  6162. for obj in objects:
  6163. obj.on_generatecnc_button_click()
  6164. def save_project(self, filename):
  6165. """
  6166. Saves the current project to the specified file.
  6167. :param filename: Name of the file in which to save.
  6168. :type filename: str
  6169. :return: None
  6170. """
  6171. self.log.debug("save_project()")
  6172. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  6173. ## Capture the latest changes
  6174. # Current object
  6175. try:
  6176. self.collection.get_active().read_form()
  6177. except:
  6178. self.log.debug("There was no active object")
  6179. pass
  6180. # Project options
  6181. self.options_read_form()
  6182. # Serialize the whole project
  6183. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  6184. "options": self.options,
  6185. "version": self.version}
  6186. if self.defaults["global_save_compressed"] is True:
  6187. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  6188. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  6189. # # Write
  6190. f.write(g)
  6191. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6192. else:
  6193. # Open file
  6194. try:
  6195. f = open(filename, 'w')
  6196. except IOError:
  6197. App.log.error("Failed to open file for saving: %s", filename)
  6198. return
  6199. # Write
  6200. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  6201. f.close()
  6202. # verification of the saved project
  6203. # Open and parse
  6204. try:
  6205. saved_f = open(filename, 'r')
  6206. except IOError:
  6207. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  6208. return
  6209. try:
  6210. saved_d = json.load(saved_f, object_hook=dict2obj)
  6211. except:
  6212. self.inform.emit(
  6213. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  6214. f.close()
  6215. return
  6216. saved_f.close()
  6217. if 'version' in saved_d:
  6218. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6219. else:
  6220. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  6221. def on_options_app2project(self):
  6222. """
  6223. Callback for Options->Transfer Options->App=>Project. Copies options
  6224. from application defaults to project defaults.
  6225. :return: None
  6226. """
  6227. self.report_usage("on_options_app2project")
  6228. self.defaults_read_form()
  6229. self.options.update(self.defaults)
  6230. self.options_write_form()
  6231. def on_options_project2app(self):
  6232. """
  6233. Callback for Options->Transfer Options->Project=>App. Copies options
  6234. from project defaults to application defaults.
  6235. :return: None
  6236. """
  6237. self.report_usage("on_options_project2app")
  6238. self.options_read_form()
  6239. self.defaults.update(self.options)
  6240. self.defaults_write_form()
  6241. def on_options_project2object(self):
  6242. """
  6243. Callback for Options->Transfer Options->Project=>Object. Copies options
  6244. from project defaults to the currently selected object.
  6245. :return: None
  6246. """
  6247. self.report_usage("on_options_project2object")
  6248. self.options_read_form()
  6249. obj = self.collection.get_active()
  6250. if obj is None:
  6251. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6252. return
  6253. for option in self.options:
  6254. if option.find(obj.kind + "_") == 0:
  6255. oname = option[len(obj.kind) + 1:]
  6256. obj.options[oname] = self.options[option]
  6257. obj.to_form() # Update UI
  6258. def on_options_object2project(self):
  6259. """
  6260. Callback for Options->Transfer Options->Object=>Project. Copies options
  6261. from the currently selected object to project defaults.
  6262. :return: None
  6263. """
  6264. self.report_usage("on_options_object2project")
  6265. obj = self.collection.get_active()
  6266. if obj is None:
  6267. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6268. return
  6269. obj.read_form()
  6270. for option in obj.options:
  6271. if option in ['name']: # TODO: Handle this better...
  6272. continue
  6273. self.options[obj.kind + "_" + option] = obj.options[option]
  6274. self.options_write_form()
  6275. def on_options_object2app(self):
  6276. """
  6277. Callback for Options->Transfer Options->Object=>App. Copies options
  6278. from the currently selected object to application defaults.
  6279. :return: None
  6280. """
  6281. self.report_usage("on_options_object2app")
  6282. obj = self.collection.get_active()
  6283. if obj is None:
  6284. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6285. return
  6286. obj.read_form()
  6287. for option in obj.options:
  6288. if option in ['name']: # TODO: Handle this better...
  6289. continue
  6290. self.defaults[obj.kind + "_" + option] = obj.options[option]
  6291. self.defaults_write_form()
  6292. def on_options_app2object(self):
  6293. """
  6294. Callback for Options->Transfer Options->App=>Object. Copies options
  6295. from application defaults to the currently selected object.
  6296. :return: None
  6297. """
  6298. self.report_usage("on_options_app2object")
  6299. self.defaults_read_form()
  6300. obj = self.collection.get_active()
  6301. if obj is None:
  6302. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6303. return
  6304. for option in self.defaults:
  6305. if option.find(obj.kind + "_") == 0:
  6306. oname = option[len(obj.kind) + 1:]
  6307. obj.options[oname] = self.defaults[option]
  6308. obj.to_form() # Update UI
  6309. # end of file